COLOUR COMPUTER
AN INTRODUCTION
TOBASK>PARTl
THE COMPREHENSIVE TEACH YOURSELF
PROGRAMMING SERIES FOR VIC 20
by Andrew Colin
77
C~ commodore
v COMPUTER
u
u
u
□
u
u
u
□
u
u
u
u
□
□
□
u
□
LJ
u
□
u
u
□
□
□
□
u
□
u
u
u
u
u
u
1. "TESTCARD" 2. "HANGMAN" 3. "SPEEDTYPE" 4. "UNIT3QUIZ" 5. "UNIT4DRILL"
6. "UNIT5QUIZ" 7. "SENTENCES" 8. "UNIT 7QUIZ"
fl| commodore
COMPUTER
©ANDREW COLIN 1 981 ©COMMODORE ELECTRONICS LTD.
■E
UNIT8PROG" 2. "UNIT9QUIZ" 3. "UNIT10QUI7" 4 "UNITIIPROG" 5 "ONiflM ii7'>
6. "SOUND DEMO" 7. "PIANO 8, "HEADS" ^"REACTION"
TAPE
2
commodore
COMPUTER
©ANDREW COLIN 1 981 ©COMMODORE ELECTRONICS LTD.
CONTENTS
This course is Part I of a series designed to
help you learn about every aspect of program-
ming the Commodore VIC computer. The present
course covers the principles of programming and
all the elementary facilities of the BASIC
programming language. It has three constituent
parte:
1 . A self-study text divided into 15 lessons or
'units', each of which deals with an important
aspect of programming.
2. 2 cassette tapes with a collection of VIC
programs, which help you study the units.
3. A flow-chart stencil like the ones used by
professional Computer Scientists. This stencil
will help you design programs to be correct,
efficient and robust.
Please note that this course teaches you to
write useful and entertaining programs for your
VIC, but it does not cover the whole of the BASIC
language. The more advanced features of BASIC
are fully explained and discussed in the second
course of the series.
CONTENTS LIST
Related Casette
Title Subject Programs Page
Introduction
Unitl
Getting Started: Setting up the VIC; Loading
programs from cassettes; Adjusting the TV set.
TESTCARD, HANGMAN
1
Unit 2
The Keyboard: The cursor; Graphics symbols;
Drawing pictures; Screen editing.
SPEEDTYPE
7
Unit 3
Pictures in Colour: Frame and background
control; Character colour selection; Reverse
field characters.
UNIT3QUIZ
15
Unit 4
Direct Commands: Numbers and strings; the
PRINT COMMAND; Effects of commas and
semicolons on spacing; Variables; the LET
command; Arithmetic and string operators.
UNIT4DRILL
23
Unit5
Stored Commands: Stored programs; the
GOTO command; Simple (uncontrolled)
loops.
UNIT5QUIZ
31
Unit 6
Practical Aids: The LIST command; Line
editing; Saving and verifying programs;
Some common pitfalls.
SENTENCES
37
Unit 7
Controlled Loops: Conditions involving
numbers and strings; Loop control by
counting, etc.; The meanings of "=" in BASIC.
UNIT7QUIZ
45
Title
Subject
Related Casette
Proarams
■ ■ VMI
Pane
Unit 8
Tracing: Tracking down errors.
UNIT8PROG
57
Unit 9
Programmed Colour: Normal and quote
screen modes; Screen representation of v
control characters; Use of position and colour
control characters in programs; The internal
clock Tl$.
UNIT9QUIZ
65
Unit 10
Input of Data: The INPUT command;
Relationships between programmer and user.
UNIT10QUIZ
73
Unit 1 1
Flow-charts: Conditional commands in
programs; Data validation; Flow-charts;
Glossaries; Program design.
UNIT11PROG
79
Unit 12
Advanced Loop Control: The FOR
and NEXT commands; Program structure.
UNIT12QUIZ
93
ll • ■ "l
Unit 13
Sounds: The VIC voices; Control of pitch,
volume and duration.
SOUND DEMO, PIANO
101
Unit 14
Data Reduction Programs: Terminating a
stream of data; Program robustness.
HEADS
107
Unit 15
Computer Games: Reaction time; the GET
command; the internal timer Tl; the RND
function; Structuring games of chance.
REACTION
117
Afterword
127
/AppcilCIIX fy
Mathematical aspects of VIC: Expressions
Precision of working
Standard functions
129
Appendix B
Answers to selected problems
135
Appendix C
Common errors
149
Index
151
INTRODUCTION
Congratulations, and welcome to the VIC
f>rogramming course. VIC is a superb machine
or playing games and producing brilliant and
exciting pictures and sounds on your TV set; but it
is also a complete modern computer in its own
right.
Computers are extraordinarily versatile;
more so, in fact, than anything except a human.
The VIC, for instance, can be switched from game
playing to be a teaching machine, a calculator,
an aid to the handicapped, a machine for finan-
cial records and stock control, a monitor for a
patient in an intensive care unit, a controller for
an industrial process, or a scientific computer
used by engineers to design buildings, power
stations and aircraft.
Computers and the systems they control are
steadily entering into our everyday lives. Already
many devices such as traffic lights, cash registers,
and banking terminals have computers behind
the scenes. This trend will continue for most of our
lifetimes. The world is passing through a
computer revolution, which will be as profound in
its effects as the Industrial Revolution was in its
own time.
The Computer Revolution can't be stopped;
but all of us can, if we like, have some influence
on the way it goes. The world is becoming
divided into two sorts of people — the
passengers and the pilots. The passengers let it
all just happen; they may enjoy using computer-
based products, or they may hate computers, or
both. They often make their views known, but
without any real effect — they can't reach the
controls, and wouldn't know how to use them if
they could.
The pilots, on the other hand, are in control
of the whole revolution. They invent new types of
computers, and think up original and useful ways
of using them. The pilots have a heavy
responsibility, since it rests on them to steer the
world towards peace, freedom and plenty, and
away from the nightmare society often depicted
in Science Fiction.
What sets apart a pilot from a passenger?
Only one thing: understanding the way a
computer works. Of course there are different
levels of understanding. Most people understand
how to use a "Space Invaders" machine even
though they couldn't explain the mechanism to
you. (Yes— there is a computer inside.) The level I
am thinking of is much deeper. It is so thorough
and complete that you can make a computer do
anything you want it to, in the way of games,
teaching activities, or serious industrial or
medicafapplications.
To have this power over your computer, to
make it into a fast, accurate obedient and willing
slave, you must be able to program the machine.
Programming is the key to becoming a pilot.
This course is all about programming. It
relates to the Commodore VIC, but once you have
mastered VIC programming you wilj find it
simple to transfer to any other computer, large or
small.
The more programming you do, the easier it
becomes. Most people can learn how to program
if they give themselves a fair chance, and so can
you. You do not need to know much about
mathematics, but you will find it useful to have a
quiet place to reaa, think and use the VIC, and it is
best to give yourself plenty of time to complete the
course. Don't rush!
The course is split into fifteen 'units'. Each unit
will take you one or two solid evenings' work, on
average. Most of the units include some reading,
some practical work on the VIC, some
programming, and a 'self-test' questionnaire to
measure how well you have understood the unit.
Every unit contains some 'experiments' which you
should tick off as you do them.
When the units ask you questions, they
generally give you spaces to write your answers.
Use them. Write with a soft pencil, and have a
rubber handy, so that your answers can be
rubbed out if you pass the VIC course on to
someone else. If your copy of the course already
has the answers written in, go through it and
erase them before you start studying.
Programming is a tight-knit subject in which
ideas depend closely on each other. Topics you
learn about in earlier units are mentioned and
used in the later ones without any further
explanation. For example, you won't be able to
make head or tail of unit 1 unless you have read
and understood all of units 1 to 9. This makes it
hriportaitf Ihqt you^ in the order
they are given.
When you start work on a new unit; begin by
reading, quickly right through it from beginning to
end'. You won't ge*much of ^detofl^bu^youwifl
formqnidea of Ihekind 'of; ^topics you are going to
study./ .<
Next,w<^
part malierSj and M parts which seen? the
hardest matter the most'. Don't skip anything, but
try to understand every point. Whei* ypu feel
you've' learned something, repeat it to yoursetf in
your own words. Don't be upset if you find you
nave to read parts of the unit several times oyer,
or even go back to an earlier unit to clear up
some awkward point. This is quite usual with a
technical subject.
Programming is like playing a musical
instrument: you can only learn it by practice. You
must therefore complete all the programming
problems in the course. As soon as you can, start
making up and solving problems of your own.
When you complete the course, you'll be
able to use the VIC for many different purposes.
For instance, you can have it administer tests or
quizzes, you can make it play games which you
invent yourself, and you may find it useful for
sums and accounts. The games or other applica-
tions can include coloured pictures to your own
design, and sounds to emphasise your meaning —
beautiful tunes or rude noises!
Programming is, however, a very large sub-
ject, anano one could do it full justice in a single
course. After a while you will probably want to
take your programming further. You may, for
instance, be interested in solving more compli-
cated problems, or in using the VIC as a control ler
for a model railway or private telephone
exchange. To make this possible, Commodore
are producing a set of aavancediprogramming
courses. . . .
Well — enough talk. It is time you started on
Unit 1. Good luck!
This unit helps you get started with your VIC.
It explains a number of rather ordinary matters;
practical questions which often raise serious
problems when people buy their first computers.
To learn programming you need the right
surroundings. Find a auiet comfortable place,
and timetable yourself long periods (at least 2
hours) atatimeof day when you are not too tired
to concentrate. Do everything you possibly can to
avoid disturbance — put a notice on the door,
take the telephone receiver off the hook, and tell
everyone in your family that you are busy: there is
nothing that makes programming more difficult
than constant interruptions!
If you have already installed your VlCand
used it, you can skip straight through to experi-
ment 1.1. Otherwise, read quickly through the
unit even if you know what it is all about; you may
still find it useful.
First, arrange your equipment and connect it
to the mains. The VIC, power supply and cassette
go on the desk or table in front of you, and the TV
should be at least 6 feet (2 metres) away if it is a
small one, or even further if it has a large screen.
The pictures and text produced by the VIC are
auite large enough to be read at normal viewing
distance, and you will find — if you try it — that
working with a screen close to your face is very
irritating and tiring.
The various units connect together as shown
in the diagram.
All plugs should slide into their sockets with
gentle steady pressure. Never use force, but look
carefully at the pin arrangements of the plugs and
sockets before you try to join them.
VIC is an extremely robust machine, but
plugs and sockets do get worn or damaged if
they are plugged and unplugged too many times.
Once your vlt is set up, aim to leave it undisturbed
as long as you can.
If your TV set does double duty as a broad-
cast receiver, get an aerial switch unit which lets
you keep the VIC and the ordinary aerial both
connected all the time.
Both VIC and the TV can be run from a single
extension power lead with twin power outlets.
Such a lead gives you great freedom in deciding
how to arrange your home computer system.
Now you are ready to switch on.
Turn on the TV, ana select a channel which is
not normally used for broadcast reception.
(For example, if your set is tuned to receive BBC1 ,
BBC2 and ITV on channels 1 , 2 and 3, you could
use channel 4.) The set will make a lot of noise,
and you may turn down the sound.
Next, power up the VIC, using the switch on
the side at the right. If all is well, the red POWER
lamp will glow, but unless you are very lucky, the
TV set will still not show a picture.
Now go back to the TV, and adjust the tuning
of the channel you have selected. The exact
method of tuning varies according to the make of
the set, and is always explained in the manufac-
turer's instructions; but in most cases there is
either a small knob or a screw associated with
each channel. Sometimes the tuning controls are
POWER
CORD
SOCKET
RF MODULATOR
TO TV
AERIAL
SOCKET
hidden behind a small panel. If you have to use a
screwdriver, don't poke it inside the set, as you
could easily get a nasty electric shock.
As you turn the tuning control, a picture will
suddenly appear:
The central square is white, with a cyan (light
blue) border. You may have to adjust the line hold
and frame hold controls to get a steady picture.
If you don't get this picture, or if the picture
comes up in black and white only, turn the VIC off
for a few seconds and try again.
If you have any difficulty, check the following
points:
• Is the TV set working? Try it on ordinary
broadcast reception, and have it repaired jf
heed be.
• Is the VIC power light on? If not, check:
(a) That there is no general power failure
•(b) That some other device (table-lamp or
hair-dryer) will run from the socket you
are using. If not, try changing the fuse in
the extension lead plug.
(c) That the fuse in the VIC power supply plug
is intact (try a new fuse).
(d) That the power supply is firmly plugged in
to the VIC.
• Is the VIC properly connected to the aerial
socket on the TV?
If your system still doesn't work, take it back
to your dealer for advice and repair.
The message now on your screen consists of
a number of 'characters' including letters,
numbers and symbols such as *. These
characters are always the same size, and when
the screen is full it holds about 500 characters.
The first line on the screen identifies the
product: a BASIC system designed and manu-
factured by Commodore Business Machines. The
'V2' is a version number which may change from
time to time.
The message on the next line of the screen
tells you how much memory there is in your
machine. Every computer needs a 'memory' to
store details of the job it is doing for you. Memory
is measured in 'bytes', each of which can hold just
one symbol or character of information. The
more memory, the more complex the task the
machine can handle.
If youore juststarting you will probably have
bought the smallestsystem, qnd the correct figure
is 3583*. If you expand your VIC by buying and
putting in extra memory, the figure will be larger.
If the number on the screen is less than 3583,
or different from its usual value, it is a sign that the
VIC is broken. It must be returned to your dealer
for repair.
The third line tells you that VIC is now ready
to Obey commands which you type on the
keyboard.
The next. line displays a flashing square.
This is called the cursor. When you type a
command on the keyboard, the cursor shows you,
in advance, exactly where each character will be
displayed. For example, try the following:
PRINT 5 + 8 1
PRINT
SPACE
5
RETURN
key. Thi
5 + 8 and press the
right of the keyboard.) (Before you start typing,
touch the mm key to make sure it is not locked
down.) As you type each symbol, (except
I ) it appears on the screen and the
cursor moves on by one place. The prime
function of the m||tfH key is to make the
computer carry out an instruction. In this instance
to print (that is to display) the result of adding
5and8!
*Th/s figure may be a little different in later
versions of the VIC.
EXPERIMENT
11
To do anything useful, the VIC must have a
program. Programs are often stored on cassette
tapes, and this first experiment will give you
practice in loading a program from a tape into
the VIC. Follow these instructions carefully:
1 . Make sure that the cassette unit is plugged into
the VIC.
2. Press STOP on the cassette unit.
3. Open the holder on the cassette unit, take out
any tape which might be there already, and
put in the TESTCARD tape — label uppermost
and with the tape window facing towards you.
Close the holder. If it does not close flat do not
force it but make sure you have put the tape in
the right way.
4. Press the REWIND key on the recorder. Watch
the cassette through the window, and if you
see it spinning, wait till it stops. Please make
sure you are at the beginning of the tape.
5. Press the STOP key on the recorder.
6. Now type the following message:
LOAD "TESTCARD'
This takes 15 key strokes in all, counting " as a
single stroke. To produce the " symbol, you will
need to find one of the two
keys (either will do) and hold it
down while you hit the key marked
Remember to release the Pj^gHJ key as
soon as (but not before) the " appears on the
screen.
You have to get the message right. Some very
common faults which you should avoid are:
Typing with the ttittl key down. You will get a
strange pattern with lines, hearts and spades,
and nothing will happen.
Using two single primes ' ' instead of a double
quote ".
The VIC will reply
?SYNTAX
ERROR
READY.
and you can try the command again on the
next line.
Putting a space between " and T, TEST and
CARD, or D and".
Typi ng the letters R E T U R N instead of using
the mnyim (,-ey
Nothing will happen.
Using digit instead of letter O in the word
LOAD.
If you make a mist ake, y ou can always 'rub
ouf by tapping the lillS key. Each depression
erases one character and moves the cursor
back one place.
7. If you give the message correctly (or even if
you make a mistake in spelling the word
TESTCARD) the machine will reply
PRESS PLAY ON TAPE
. giving a picture like this:
★ ★ ★ ★ CBM BASIC V2 * ★ ★ *
3583 BYTES FREE
READY.
LOAD "TESTCARD"
PRESS PLAY ON TAPE
Press the PLAY key on the cassette unit. Wait
about a minute for the program to be loaded.
If the tape runs on and on, and the screen
shows several messages like
FOUND TESTCARD
FOUND HANGMAN
you have probably mis-spelled the name
TESTCARD. Stop the computer by pressing yjjjf ,
and go back to step 1 .
If the tape runs on and on, and nothing
happens, make sure you aren't trying to play a
blank tape. If not, suspect the cassette unit and
take it (and the VIC) back to your dealer for a
checkup.
When the program is finally loaded, the
machine will say
READY.
Start the program by typing
RUN
(4 key depressions)
EXPERIMENT
1-2
The first program shows you the range of
colours the VIC can handle, and helps you make
fine adjustments to your TV set.
Turn up the volume, and adjust the channel
tuning very gently until you hear music being
played clearly and with as little background
noise as possible. (You may recognise the piece,
which is Offenbach's Cancan from the opera
"Orpheus in the Underworld".) Then set the
brightness and colour controls so that the colours
correspond to their names and look right when
seen from a reasonable distance.
You will see that the picture appears on a
cyan frame. You can change the frame to any
other colour by holding down the key
and typing one of the 8 colour keys in the top row.
They are labelled:
BLK WHT RED CYN PUR GRN BLU YEL
Eventually, you can stop the TESTCARD
program by pressing the UUif key.
When you press this key (or whenever a
program stops for any reason) the screen shows
a message like
BREAK IN 560
READY.
The 560 in the example could be any number.
BREAK doesn't mean the VIC is broken; it just tells
you that there has been a break in the sequence
of commands which makes up the program.
The READY is a sign that the VIC is ready to
obey another command from the keyboard.
If th e sound c ontinues hold down
and hit miiH / this will always silence the
VIC and clear the screen.
Sometimes, when the TESTCARD program is
stopped in the middle of a tune, the VIC goes on
sounding the note it played last. Y ou ca n stop the
note playi ng by hold ing down the UtiJ key and
pressing ggjUfig which is the key near the
top right of the keyboard.
You may find it convenient to use the
TESTCARD program whenever you need to
readjust your set.
Experiment 1.1 Completed
Experiment 1 .2 is a word-guessing game
designed to help you get the feel of the keyboard.
Load the program from the cassette; it is called
HANGMAN, so you type
LOAD "HANGMAN" and press the!
key.
★ ★ ★ ★ CBM BASIC V2 ★ * ★ ★
3583 BYTES FREE
READY.
LOAD "HANGMAN"
PRESS PLAY ON TAPE
When the program is loaded and the READY,
message comes up, type
RUN
and the game will start. If you don't know how to
play, just keep trying letters and watch (and listen)
to what happens. You will quickly pick up the idea.
Play the game as long as you like, and use
the opportunity to get accustomed to using the
letters on the keyboard.
Experiment 1.2 Completed
NOTE:
Each program supplied with this package is recorded
twice. The duplicate block of programs follows the
initial recording of the block on the cassette.
u
u
u
□
u
u
u
□
u
u
u
u
□
□
□
u
□
LJ
u
□
u
u
□
□
□
□
u
□
u
u
u
u
u
u
UNIT:2
EXPERIMENT 2-1
PAGE 7
EXPERIMENT 2-2
8
EXPERIMENT 2-3
10
EXPERIMENT 2-4
11
Welcome back. This unit is about the VIC's
keyboard, and tells you how to use it to write
messages and draw pictures on the screen.
If you have ever used an ordinary typewriter,
the computer keyboard will look familiar. You
will find the letters, the numbers and most of the
signs in their accustomed places, and there are
the usual shift and shift lock keys — although they
work a little differently on the VIC.
On the other hand, don't be put off if you
have never done any typing. You will need a little
more time to get used to the VIC keyboard, but
that is all the difference it makes.
For this unit only, please don't use the
key unless we say you should. As
you saw in Unit 1 , this key is the one which makes
the machine actually do something for you, such
as loading a program or adding up some
numbers. At present, just to use the screen, you
don't need the computer's help. If you do press
, the VIC will only try to obey the
message or picture you have just typed,
misunderstand it ana spoil its appearance.
Another symbol you should avoid just now is
the double quote mark ("). This sign has a special
meaning, and alters the way the screen reacts to
many of the other keys on the keyboard. If a
double quote is showing on the screen it can be
much more difficult to draw useful pictures. You
will learn all about this character in a later unit; but
for now, keep off I
You may find this list of "don'ts" quite
alarming. Here is another one: Don't Worry!
Unlike computers in Science Fiction, the VIC has
no 'self destrucf command. It is absolutely
impossible to damage the machine by typing on
the keyboard. Some patterns of characters which
contain "or ■■■ will make it behave
quite strangely, and a few sequences, which you
might hit by chance if you are careless, will stop the
computer from responding to you at all. These
troubles are only temporary: you can always cure
them by switching the computer off for 30
seconds, and then on again.
EXPERIMENT
2-1
The 66 keys on the keyboard are divided into
two categories:
• 50 Symbol keys, which make the VIC draw
characters on the screen.
• 1 6 Function keys, which control the way the
characters are drawn.
The function keys are:
CLP ■ INST
HOMEB DEL
CRSRBCRSRB SHIFT
and
The ten symbol keys marked 1 to a Iso have
certain control functions.
Compare the keyboard with the chart
below, an d ide ntify the various control keys.
Press the 690 several times and note that it has
two positions — up and down. Finally, make
sure that it is in the 'up' position.
CLR ■ INST
HOME I DEI
RUN | SHIFT
STOP ■ LOCK
EXPERIMENT
2-2
n
Now start your machine in the normal way.
Just below the READY, message you will see the
-■- flashing cursor.
In this experiment we examine how the cursor
moves when symbols are drawn on the screen.
The purpose of the cursor is to show you where
the next typed character will appear. Type a few
letters, and watch the cursor move across the
screen. Notice that every character replaces the
cursor, which then shifts to the next position.
Now fill up the whole line with letters, until the
cursor is at the extreme right of the white area.
Type one more letter and watch what happens:
the cursor jumps to the beginning of the next line,
all by itself.
Before going on, count the number of letters
across the screen, and fill in the box:
There are
spaces for characters in
each line on the screen.
Next, type some more lines, and keep going
until you reach the bottom line of the screen. Count
the number of lines showing and write the number
in the box below. Remember to include the blank
lines above and below the message:
3583 BYTES FREE
There are
characters.
lines in a screenful of
Now fill in the last line until the cursor
reaches the lower right-hand corner of the screen .
Type one more character and watch the cursor.
The whole screen moves up and the cursor moves
to the beginning of the next blank line which
appears at the bottom. Any blank lines are
bought at the expense of the top-most ones,
which have now vanished. The top lines have
gone for good, and there is no way of bringing
them back, unless copies are stored somewhere
else.
Fill in a few more lines, and confirm that the
system always gives you room at the bottom of
the screen for more text.
Experiment 2 J Completed
VIC has some 50 symbol keys, but it can
display a much larger number of different
symbols. They include letters, numbers, punctua-
tion and mathematical symbols, and a wide range
of 'graphics' or simple shapes which can be
combined to make up different pictures. All these
different charact ers can be selected by using
either of the two m|j|flH keys (they are con-
nected together inside the compute r) and the
special 'Commodore' key labelled
Restart your machine and type the line
«-1234567890 + -£QWE-RTYUI
(These are all the symbol keys in the top row
and some of those in the second.)
★ ★ ★ ★ CBM BASIC V2 ★ ★ ★ ★
3583 BYTES FREE
READY.
<-1234 5678 90 + -£QWERTYUI
8
Now hold one of the ^HH0 |< eys d own
and type the line again. You will get an almost
completely different line of symbols (including a ",
but this will not trouble you if you follow the
instructions). Copy the symbols into the second
row of the table below, and notice how some of
the graphics (for example those on U and I) fit
together. If your TV picture is a bit smudged it may
help you to look at the signs embossed on the
keys themselves. Notice how the graphic symbols
usually reach the edges of the little squares they
occupy, so that they can be made to touch each
other.
SYMBOL
1
2
3
4
5
6
7
8
9
+
£
Q
W
E
R
T
Y
U
1
SYMBOL
o
p
@
★
t
A
S
D
F
G
H
J
K
L
•
•
•
Z
X
c
V
B
SYMBOL
N
M
•
/
Next, type the line yet a third time, but this
time holding down the 19 key. Many of the
signs are different again. Copy the line into the
third row of the fable.
To examine the other graphics, repeat the
experiment with the lines
OP@*fASDFGHJKL:; = ZXCVB
N M , . /
Fill up the last line with spaces.
Note and remember that the digit is different
from letter 'O'. You should always use the to
show that you mean the number, not the letter.
Press 19 and ■IH down together.
Many of the capitals on the screen will change
into lower-case letters. Press the keys together
again and the capitals come back. In general,
you can use either a full set of graphics, or a
restricted set and lower-case letters, but not both
at the same time. The use of small letters will be
explained in the second volume of this course.
Experiment 2.2 Completed
EXPERIMENT
2-3
anything underneath it.
Try moving the cursor to the first * on the
right, and then putting in four = signs. The top line
becomes
= = = = CBM BASIC V2 = = = =
and the cursor moves to the left of the next line.
1
= = = = CBM BASIC V2 = = = =
3583 BYTES FREE
READY.
CLR
HOME
f>
CRSR
•U-
and
CRSR
So far you have been limited to displaying
characters strictly in sequence, left-to-right and
from the top down. This is a tedious way to draw a
picture, and it would be far more convenient if
you could place your textand graphic symbols at
any position you chose.
This can be done with the cursor control keys,
of which there are three
When you type WU by itself, it moves the
cursor back 'home', which is the top left-hand
corner of the screen. Restart your machine (just in
case the previous experiment left it in a funny
mood) and strike this key. You will see the cursor
move to the * at the top left of the screen. The
* remains visible because the cursor is
transparent; but if you type another character (or
★ * CBM BASIC V2 ★ ★ ★ ★
3583 BYTES FREE
READY.
a space) the symbol under the cursor is replaced
by the new one. Try putting an = instead of the *.
Type = three more times, giving you
= = = = CBM BASIC V2 ★ ★ ★ ★
as the top line of the screen.
You may now want to alter the * * * * on
the right to = = = =, so as to keep the line
symmetrical. If you move the cursor along by
typing spaces, you will rub out the title in the
centr e of the line. The correct way is to use the
■if key. Every time you hit this key, the cursor
moves one place right, but without spoiling
If you hold the H3i key down continuously,
then after a short pause the cursor moves by itself
at a rate of about 1 places a second, line after
line. This is useful to move around quickly.
When the HSU key is struck while
is held down, the cursor moves backwards. When
it reaches the beginning of one line it moves up to
the end of the previous one.
Next try going back to the first line, and
changing the = signs back to *'s .
Move the cursor down to the bottom line of
the screen and watch what happens when you
move past the end of the line: the whole screen
moves up just as if you had added another
character.
Now go back 'home' and try to move the
cursor backwards. The screen does not move
down as you might have expected; nothing
happens at all, and the cursor stays in the same
place.
The IBM key moves the cursor up or down
a whole line at a time. Try some experiments with
it, and make sure you understand how it works.
Next, fill up the screen with a few characters
and graphics, and then press IttU while holding
down the shift key. The cursor moves home and
the screen is cleared, giving you a fresh screen to
work on.
Fill in the following table:
Key
No shift EffeCt Shift
I CLR 1
IhomeI
Moves cursor
home
00
Moves cursor 1
place backwards
1 1
1 CRSR 1
1 Ti- I
Now practice making drawings on the screen
using the graphics symbols and cursor control
keys. Start with some simple geometrical shapes
like squares, oblongs, triangles and small circles.
If you make a mistake, move the cursor back and
type the right character. 'Space' will get rid of
characters which are in the wrong place.
When you have got the feel of using the
graphics, draw a box, like this, with your name in it .
CHRIS
BLOGGS
11
Now draw some playing cards, with curved
corners and the right symbols (we suggest you
keep to black cards worth 10 or less).
Finally, if your artistic talent is up to it, trying
something like an animal, a space-ship or a
human face.
Plan your picture first, using the grid below.
Experiment 2.3 Completed
EXPERIMENT
2-4
Everyone makes mistakes when typing. If
you get a single letter wrong in the middle of a
word, you can correct it with the cursor control.
For example, if you type AUSTRAPIA when you
mean AUSTRALIA, you can move the cursor back
over the P and change it to an L. Try it!
Unfortunately, if you get the wrong number
of letters (too few or too many) this method won't
help you. A more powerful facility is provided by
the litil key, which lets you insert or remove
characters from the screen.
When you type 139 by itself, it rubs out the
character to the left of the cursor and shuffles all
the other characters on the line one place left so
as to fill in the empty space.
For example, suppose that you mistakenly
type INXDIA when you mean INDIA. You want to
get rid o f the X, so put the cursor over the D, and
hit MS3M .TheXdisappears,andDIAallmoveup
to the left, leaving INDIA (without a space in the
middle).
Now try using the EES key to make some
corrections, as follows:
CHAIN A to CHINA
EEGYPT to EGYPT
FINLANDIA to FINLAND
AUSTRALIA to AUSTRIA
In practice, the most common use of the I
key is to get rid of the character or characters you
have just typed. The key will remove the last
symbol ana reposition the cursor, all in one
mov ement. You will soon get accustomed to hitting
ABB whenever you make a t yping mistake.
The other function of the 199 key can be
called up by typing it as a shifted character: that
is, holding down the MBHB key when
is struck. This function is used to insert spaces into
the middle of words or lines. These spaces can
then be filled up with characters in the ordinary
way.
Try the following example, which involves
changing AUSTRIA into AUSTRA LIA.
Clear the screen ( anc j
) and
type
AUSTRIA
Move the cursor back over the I.
Hold down the shift key and strike I
twice. Each time the IA moves one place to the
right. The cursor stays in the same place, so after
two moves you get _
- 2 spaces
austr-; '
cursor
Now finish by filling in AL. Move the cursor
past the end of the word.
key, clear the
To practice using the
screen, fill it up with the list of words on the left,
and then change each one to the corresponding
word on the right:
HOTEL
MOTEL
MICROPHONE
MICROCOMPUTER
PLYWOOD
WOOD
ANGLE
ANGEL
CHAP
CHEAP
WRITER
WRITTEN
ACTOR
AUTHOR
BALL
BARREL
WIRE
REWIRE
FLOWER
FLOUR
MOON
MORON
PIDGIN
PIGEON
TACT
TACIT
HORSE
HOARSE
WING
WARRING
TAXI
TAX
RED
READY
MERRY
MERCURY
JOVE
JUPITER
PAL
PASCAL
BACK
BASIC
JAVA
JAMAICA
And now change them all back again.
Experiment 2.4 Completed
The Unit 2 program is entitled SPEEDTYPE. It
helps you to get familiar with the keyboard. Load
it (by typing LOAD "SPEEDTYPE"), start it with the
RUN command and practice using it as much as
you feel is necessary.
u
u
u
□
u
u
u
□
u
u
u
u
□
□
□
u
□
LJ
u
□
u
u
□
□
□
□
u
□
u
u
u
u
u
u
UNIT:3
EXPERIMENT 31
PAGE 15
EXPERIMENT 3 2
16
EXPERIMENT 3 3
18
EXPERIMENT 3-4 20
VIC is a colour computer. This unit introduces
you to some of the ways you can get the machine
to draw many-coloured pictures on your TV
screen.
If your TV set is a black-and-white model, do
not expect brilliant results from Unit 3! You should
work through it just the same.
15
EXPERIMENT
3-1
Use theTESTCARD program (unit 1 ) to make
sure that your TV receiver is properly adjusted.
Stop the program by holding down yQ| and
striking ^uUg .
You will see that the cursor at this stage is
blue. Now the cursor can change colour, and as
well as telling you where the next symbol will be
placed, it also indicates wha t colo ur it is going to
be. Try typing a sequence of symbols (I
and I keys) and note that they appear in blue,
which is the present colour of the cursor.
(Where a character has a lot of fine detail the
apparent colour may not always be correct. This
is a consequence of using an ordinary TV set,
which has a narrow RF bandwidth. The difficulty
can be cured by buying a more expensive colour
monitor, but it is hardly worth it unless you plan to
display a great deal of text in different colours.)
Figure 1
EXPERIMENT
3-2
The colour of the cursor can be changed at
any time by typing one of the 8 colour keys while
holding down the |< e y -r ne colour keys
are marked 1 to 8, and also carry abbreviations
of the colours they control.
I and strike the colour
Hold down I
keys in succession.
When you hit 1 (BLK) the cursor changes to
black
When you hit 2 (WHT) the cursor disappears.
This is because it is now the same colour as
the background, and therefore invisible. This
colour is called 'white'.
The other keys change the cursor to red,
cyan, purple, green, blue and yellow,
respectively.
Now try making some coloured pictures. A
good way to start is to mak e som e coloure d bar s
of various lengths. Use the graphic (^3
and U) to build up each bar. For example, to
make a red bar 5 symbols long, first hold down
| and type 3 (RED); this will ch ange the
cursor to red. Then hold down \2M and strike
U five times.
When you have got the feel of the colour
keys, try drawing an "election results chart" as
shown in Figure 1 . Keep the lettering black to
emphasise the colours of the bars.
Experiment 3.1 Completed
As well as looking after the colours of
individual symbols, the VIC can control the
colours of the outer frame and the background
on which the symbols appear. VIC does not have
any dedicatee! keys to control these colours, and
the only way to change them is to give a special
command.
Type POKE 36879,24 Check it carefully,
correct it if necessary, and then strike the
key. The frame on the TV screen
immediately turns black.
This special command has three parts:
POKE: This is called a keyword.
36879: This is called an address. It identifies
the part of the VIC which looks after
the colours of the frame and back-
ground. Any special command to
change either of these two colours
must always refer to this address.
24 : This is a code, which indicates
"Black frame, white background".
To select other colours and combinations, it
is useful to know the 'colour codes'. There are 1 6
different colours, each with its own number. Any
of the 1 6 can be used as the background colour,
but only the first 8 can be selected colours for the
frame or the symbols. The colours and their
numbers are:
Colour
Number
Comments
Black
White
Red
Cyan
Purple
Green
Blue
Yellow
1
2
3
4
5
6
7
Can be used for back-
ground, frame and
symbols. The codes are
I less than the keys used
to select the colour of
the cursor.
Orange
Light Orange
Pink
Light Cyan
Light purple
Light green
Light blue
Light yellow
8
9
10
11
12
13
14
15
Can be used for back-
ground only.
. The frame and background colours must
always be set by the same command. The 'code
number' can be worked Out as
16 x background colour number + frame
colour number + 8. ;
For example, a picture with a pink back-
ground and a purple frame could be called up by
typing
because 172 = 16 x
pink
POKE 36879, 172
[~4~| +8
purple
10
If you don't know your 16-times table too well
dfewt
chart usef
(and few people do) you may find the following
3ful:
Select a few colour combinations, POKE them
by using the appropriate special commands, and
find one or two you really like.
Background
Colour
Frame Colour
Black
White
Red
Cyan
Purple
Green
Blue
Yellow
Black
8
9
10
11
12
13
14
15
White
24
25
26
27
28
29
30
31
Red
40
41
42
43
44
45
46
47
Cyan
56
57
58
59
60
61
62
63
Purple
72
73
74
75
76
77
78
79
Green
88
89
90
91
92
93
94
95
Blue
104
105
106
107
108
109
110
111
Yellow
120
121
122
123
124
125
126
127
Orange
136
137
138
139
140
141
142
143
Light Orange
152
153
154
155
156
157
158
159
Pink
168
169
170
171
172
173
174
175
Light Cyan
184
185
186
187
188
189
190
191
Light Purple
200
201
202
203
204
205
206
207
Light Green
216
217
218
219
220
221
222
223
Light Blue
232
233
234
235
236
237
238
239
Light Yellow
248
249
250
251
252
253
254
255
Experiment 3.2 Completed
EXPERIMENT
3-3
You may have noticed some strange gaps in
t he gr aphics chara cters; for instance w e have
but not ; we have but
Ho r E
not I^H or . Furthermore it seems impos-
sible to fill a complete square with colour and
therefore to build up large areas of the same hue.
The reverse field facility comes to our help.
When a character is displayed in reverse
field, the colours of the characters and of its
background are swapped. Try the following
experiment:
Restart the VIC, select purple as the cursor
colou r, and ty pe a few characters, including
and a space. Now hold down
land the 9 key (also labelled RVS ON).
Then release ■■■and type a few more charac-
ters. They will appear in white on a purple back-
ground, instead of purple on white. In particular
EH come s out as , 1^1 and are
changed to , and a space
appears as a solid block of purple. We say the
VIC is in reverse mode.
To bring the following characters back to
normal mode, hold down HIV and type the
key (labelled RVS OFF).
The cursor does not show whether the
machine is reverse or normal mode. If you are
using many reversed symbols it is easy to forget,
and to be in some doubt as to how the next
character will appear. This difficulty can be
resolved in two ways:
(a) Type the next character and look at it. If it is
wrong, erase it, change the mode, and try
again.
Type the RVS ON or RVS OFF key, as
appropriate, before you type the next symbol.
If the machine is already in the right mode this
will not make any difference.
(b)
The best way to fill up the screen with blocks
of colour is to use reversed spaces. The space bar
is a 'repeating' key, and if you hold it down it will
generate a sequence of spaces at about 1 per
second.
Drawing national flags makes a good way
of getting practice in the use of colour. The
easiest type of flag to reproduce, is one with hori-
zontal stripes, such as that of Luxembourg.
To paint this flag, set the frame to a suitable
colour (say black) and the background colour to
the same as the bottom left-hand corner of the
flag (blue). This is done by
POKE 36879, 104 1
(The '1 04' is copied from the table on page 1 7.)
Next move the cursor home, select red and
reverse mode (hold downHHfll and type RED
and then RVS ON). Then hold down the space bar
and fill up 8 lines with reversed red spaces.
Next, select white and fill up 7 lines with
white reversed spaces.
Lastly, change the colour to blue. This will
make the cursor disappear and leave an 8-line
blue area at the bottom of the flag.
It is important to set the background colour
to one of the colours which appear on the picture,
otherwise you will be unable to hide the cursor
when the drawing is complete. Likewise the
frame colour should be different from any colour
which appears in the flag itself.
When you have mastered horizontal flags,
try one with vertical stripes, such as Italy. Those
with crosses (Switzerland or Iceland) are also
worth drawing.
Even more difficult are flags with diagonal
elements such as Tanzania or Czechoslovakia.
The parts of the flag near th e slop ing li nes m ust
3 orB .
be made with the graphics
suitably reversed if necessary. If you think about it
you'll see that the background colour must be
chosen so that it is on one side of every sloping
line. In the case of the Tanzanian flag, a suitable
background is yellow; blue wouldn't do because
there would be no way of drawing a green and
EXPERIMENT
3-4
yellow element.
A typical line about half-way down the Tanza-
nian flag would be entered as:
The commas as well as the word "and"
shown above are simply to show you the different
commands so that they are easier to follow. They
should, of course, not actually be used when
drawing the flag.
If you feel sufficiently patriotic, you might try
the flags of St. Andrew, St. David, St. George or
St. Patrick. The Union Jack is formidably difficult
to draw (even without a computer) and could well
be omitted.
Experiment 3.3 Completed
Draw the best coloured picture you can,
using the full scope of the VIC. You may find it
useful to plan your picture first, using a sheet of
squared paper ana some coloured crayons.
20
Experiment 3.4 Completed
The program which goes with Unit3 is a quiz,
and can be loaded by typing
LOAD"UNIT3QUIZ"
u
u
u
□
u
u
u
□
u
u
u
u
□
□
□
u
□
LJ
u
□
u
u
□
□
□
□
u
□
u
u
u
u
u
u
In the first three units of the course we have
concentrated almost wholly on the VIC keyboard,
and on using it to display text and paint pictures
on the TV screen. This is sound preparation for
the next part of the course, where we look at
some of the functions the VIC can do on your
behalf.
As you already know, VIC will do various
jobs when it is commanded to do so. The neces-
sary commands are written in BASIC, a simple
ana popular computer language first devised by
Kemeny and Kurtz at the Dartmouth College,
USA. BASIC has its own rules of grammar just like
any other language, but you may be glad to hear
that they are simple to learn, and that you will
easily memorise them through practice, without
any special effort.
Every BASIC command starts with a 'keyword'
such as LOAD or POKE or PRINT. This tells the
computer what type of command is meant.
Similarly , every command ends with the
key. This has two different
meanings:
If the keyword is the first word on the line,
is a kind of starting gun: "Now go
and do it". For example, if you type
LOAD'TESTCARD"
the actual loading starts when the I
key is pressed. The other interpretation of
is discussed in the next unit, but
here is a short preview:
If the keyword in a BASIC command has a
number in front of it — such as
3 PRINTS + 7
then the BHHflilMB key is a signal not to obey
the command, but to store it away for later use.
In this unit we concentrate on the first inter-
pretation. Our commands will not have numbers
in front of them, and HiiH will be a cue
for the VIC to take immediate action.
EXPERIMENT
41
One of the most useful and flexible com-
mands is PRINT. It makes the computer work out
something for you and display the result on the
screen. The word PRINT is used because the
original BASIC system at Dartmouth relied on
mechanised teleprinters which really did print the
answers on rolls of paper.
Experiment 4.1 is arranged in three stages.
First, we try out a number of different PRINT
commands and make careful notes of the results.
Next, we discuss the features of the command
which have shown up in the examples; and finally,
we examine some new PRINT commands, and try
to predict what the computer will do with them.
The answers can be checked by using the
computer itself.
Begin by typing these commands, ending
each one with the HHHHtfli^^B key. Be sure to
get the commands right, using the cursor control
keys to correct your typing if need be. Make a
careful note of the responses in the boxes
provided. The first two boxes are already filled in
for you:
PRINT 999
999
READY.
PRINT "HELLO"
HELLO
READY.
PRINT— 56
PRINT 3+4+4
PRINT 5*7
PRINT 27/7
PRINT "VIC COMPUTER"
PRINT VIC
PRINT 3,5
PRINT 3;5
PRINT "RABBIT", "DOG"
PRINT "CAT"; "FISH"
PRINT "3+5"
PRINT 29-1 2; "LIONS"
PRINT 1 ;2;3;4
Before reading on, study your notes carefully
and see how many different features of PRINT
you can pick out. One common aspect of the
answers is that they are followed by READY, but
this is true of any command obeyed directly from
the screen, so it hardly counts as a special
property of PRINT!
Here then are the most important points of
the PRINT command;
1. The command can handle both numbers and
strings, and it does so in different ways:
A number can either be given explicitly (like
999} or in the form of an expression or "sum"
which the computer works out. The expres-
sions in our trials were 3+4+5, 5*7, 27/7
and 29- 1 2, so we see that the VIC can add,
take away, multiply and divide. The signs *
and / mean multiplication and division,
respectively. (If you are interested in using
the computer for more advanced mathe-
matics calculations, you will be glad to hear
that these expressions can be as complicated
as you need. They can include brackets, and
all the special functions you would expect to
find on a scientific calculator. You are
advised to look at Appendix A, which is an
extra unit designed specially for you.)
A string is any sequence of characters
enclosed in double quote marks. The PRINT
command simply regurgitates, such d string
exactly as it was given, without trying to
process it in any way. The strings in our tests
were
"HELLO", "VIC COMPUTER",
"RABBIT", "DOG", "CAT", "FISH", "3+5"
and "LIONS".
Notice that "3+5" is not an expression, even
though it looks like one; it is enclosed in
Suotes, so it must be a string,
you want to display a string, but forget to
put quotes round it, you will probably get
(although you might sometimes get some-
thing else).
2. The PRINT command can handle two or
more quantities or strings at the same time. If
the two are separated by commas, then the
second result is spaced well across the
screen (just over halfway); If a semicolon is
used, the separation is less. In particular,
strings are not separated at all (this is how
we get "CATFISH"). Numbers displayed by
the computer seem to be separated because
every number is always preceded by a
space (or by a — sign if it is negative) and
always followed by another space. If your
records don't show this very clearly, repeat
the command
PRINT 1;2;3;4
and 'measure' the result by moving the
cursor over it.
3. Next we look at spaces i nside the command
itself. The keyword PRINT must be compact
(that is, its letters must not be separated by
spaces), and any space which is inside a
string belongs to that string and will be
reproduced. Otherwise, spaces between
strings or numbers are ignored. Thus
PRINT 3 +5;7; 8
will give exactly the same result as
PRINT3+5;7;8
This rule — that spaces in commands are
ignored everywhere except inside keywords
and in strings — is generally true for the
whole of BASIC
4. If you make a mistake in the keyword itself,
or if you supply an expression which doesn't
make sense (such as 5**7) the computer
will reject your command with the comment
?SYNTAX
ERROR
This is computer jargon for saying that you
have broken the rules of BASIC. There is
nothing for it but to correct the command
and try it again.
Now run through the following list of PRINT
commands and predict what the VIC will do with
each one. Show how the results will be spaced:
this is just as important as getting the results right
in themselves. On the other hand, don't bother
writing down READY, each time.
Some of the commands may contain
deliberate errors.
Check your answers on the VIC. If you have
made any mistakes, and can't see why you've
made them, go back and repeat the whole
experiment, until the ideas become clear in your
mind.
Note that the VIC always carries out calcula-
tions involving multiplication and division before
addition and subtraction. As examples:
PRINT 5+2*7 will give 19
and
PRINT 5+2+6/3-3 will give 6.
Command
Your prediction
VICs result
PRINT 94
PRINT 8— 5
PRINT3*2 + 5
PRINT "OH DEAR"
PRINT ENOUGH
PRINT "lit/3"
PRINT 3; 47
PRINT 2+2;2-2;2*2;2/2
PRINT "CLOUD"; "BURST"
PRIN8— 7
PRINT "18", "MICE"
PRINT 53+*7
PRINT -l;-2;-3
i ' •/
Experiment 4.1 Completed
\
EXPERIMENT
4-2
If a computer could only do one command at
a time, it would not be specially valuable to
anyone. At best, it would be about as good as a
(non-programmable) calculator. Most useful
computer jobs consist of whole sequences of
commands, controlled by sets of instructions
called "programs". As the commands in the
sequence are obeyed, there has to be some way
of 'keeping the score', of remembering how far
the job has gone, and of passing the results of one
command on to the next. The memory which
serves to link commands is provided in the form
oivariables.
Before discussing BASIC variables, we shall
give you a human analogy. Suppose you are the
score-keeper at a football match. Your instruc-
tions could be as follows:
Before the match starts, draw two boxes,
label them with the names of the teams, and
write zeros inside them, thus:
BOLTON
UNITED
vs
KELSO
CITY
Whenever either side scores a goal, replace
the most recently written number in the
corresponding box by the same numbers,
plus one. Rub out (or cross out) the old
number.
Part-way through the match, the state could
be
BOLTON
UNITED
KELSO
CITY
When the final whistle blows, use the score-
board to display the names of the teams
together with the (latest) numbers inside the
boxes, thus:
BOLTON UNITED
2
KELSO CITY
5
In this example the boxes are variables-, the
numbers in the boxes serve to remember the
current state of play, and change from time to
time as necessary; but the labels remain the same
for the duration of the match. The instructions for
using them are very simple, but foolproof.
The memory of the VIC (it probably has 3583
bytes — remember?) is a bit like a large black-
board. When the machine is first switched on the
board is wiped completely clean. Then, whenever
a variable is first mentioned the computer "draws
a box" by setting aside part of the memory, and
labels it with a name chosen bv the human user.
Then it "writes a number in the box" by storing the
appropriate value in the memory which has been
set aside.
The BASIC command which makes the com-
puter do all this has the keyword LET. Let's
examine such a command in detail:
LETX = 5
Here, the variable name is X. The VIC will set
up a box called X (if it has not already done so)
and will put the number 5 inside it. If a variable X
already exists, then no more space is set aside;
the 5 merely replaces the previous value. Study
the following cases:
X does not exist
(Case 1)
X already exists
(Case 2)
Before
(Memory empty)
37
X
After
5
5
X
X
ResultofLETX=5
When you give a LET command, the computer
just says
READY.
There is no evidence on the screen that the
machine has done anything at all. Fortunately, we
are helped by the PRINT command, which :
displays the value of a variable whenever it is
mentioned by name. Try the following sequence
of commands:
Your results
LETZ = 14
PRINT Z
LETZ = 31
PRINT Z
If you keep the right order, the fiVstvalue of Z
to be printed will be 1 4, and the second, 31 . The
first LET command both creates a variable called
Z, and gives it the value 14; the second one
merely changes its Value to 31 .
At this stage we have to give you a few
simple rules about variables and their names.
There are two kinds of variables in BASIC:
• Numeric variables, for storing numbers .
• String variables, for storing strings (e.g. words
or phrases).
The choice of names for variables is quite
restricted. A numeric variable can be called by a
single letter, a letter followed by a digit, or by two
letters. Some examples of possible names for
numeric variables are
A,X,Z,B5,TX,PQ
Names for string variables always end in
the $ sign, but otherwise the rules for string
variables are the same as for numeric variables.
Examples are
C$,Z$, P7$, DB$
To show the use of string variables, try typing
LET T$ = "GOOD "
PRINT T$; "MORNING"
The value which follows the = sign in a LET
command doesn't need to be a simple number or
string; it may be an expression, ana furthermore it
can use the current values of variables by
referring to their names. For example, look at the
following sequence of commands:
LET Q = 5
LETS = Q+3
The first one creates a variable called Q (it is
a number variable because of its name) and sets
its value to 5. The second one makes a variable
called S. It then takes the value of Q, adds 3, arid
puts the result into S. To illustrate the point, try •
running these two commands, and inspect the
result by typing:
PRINT Q;S
Now look at the following sequences and
predict the outcome of the PRINT statement in
' i case:
LET AA = 15
LET B = 33— AA
PRINT AA,B
LETD = 3
LET E = D*D+7
LET F = E— D
PRINT F;E;D
LET F=4
LETF=F+1
PRINT F
Did you get the last one right? Some people
might find it a bit tricky.
There is no limit to the number of different
values a variable can hold, as long as it only
holds one at a time. A command like
LETF = F+1
means: First work out the expression (by taking
the value of F and adding 1 )
Then put the result in box F, replacing the
previous value.
In other words, the command makes the VIC
add 7 to the current value of F.
The signs which allow us to combine numbers
in various ways are called arithmetic operators.
They are +, -, * and /. BASIC also allows strings
to be manipulated in various ways by using string
operators. Only one of them combines two
strings; it is called "concatenation" and is written
as a + sign. The operator simply attaches the
second string to the end of the first, so that
"DOG" + "ROSE" = "DOGROSE"
Look at the f ol lowing sequence of commands,
and predict the outcome of the PRINT'S. Then try
the sequence on the computer; remember to put a
space before each of the closing quotes: 1
LET B$="DOG
LETC$="BITES
LET D$="MAN
LET E$= B$+C$+D$
LET F$= D$+C$+B$
PRINT E$
PRINT F$
PRINT and LET are the two most frequently
used commands in BASIC. It is worth remember-
ing that when you use the VIC you are allowed to
replace the word PRINT by a single symbol: the
query (?). LET can be omitted altogether. A valid
sequence is
A=5
B=17
?A,B
The program which comes with this unit is
designed to give you plenty of practice with PRINT
and LET commands. It is called UNIT4DRILL.
You can stop the program when you are sure
you fully understand the use of numeric and string
variables.
Experiment 4.2 Completed
u
u
u
□
u
u
u
□
u
u
u
u
□
□
□
u
□
LJ
u
□
u
u
□
□
□
□
u
□
u
u
u
u
u
u
EXPERIMENT
5-1
The time has come to look at stored
commands. Let's begin by showing that the VIC
really can put commands away in its memory,
and then fetch them out again later.
Start up your machine (or if it is already
running another program such as SPEEDTYPE,
stop it by typing UUi ) and give the command
NEW (followed, as usual by the
key).
This command makes the VIC wipe its memory
clean, just as a teacher cleans the blackboard at
the start of a lesson. You won't see anything
happen except the READY, response, because
the memory is all inside the computer.
Next, type the labelled command
10 PRINT 13+59
(NOTE: "one zero", not "eye oh")
and follow it by pressing the ^mjjg|^^ ^
The only visible result is that the machine moves
the cursor to the beginning of the next line. The
result of the sum 1 3+59* is not worked out or
displayed on the screen. Instead, something invis-
ible has happened: the VIC has remembered the
command and put it away in its internal memory.
To verify this, first clear the screen (using the
command
and litilAi keys) and then give the
LIST
If you have done everything the right way, a copy
of the labelled command reappears on the
screen. This proves that it was in the machine all
the time.
So far, our PRINT command has been stored
and retrieved, but it hasn't actually been obeyed.
*There is nothing special aboutthe sum 13+59.
Any other PRINT command would have done
equally well for this example.
The computer is still to tell us what 1 3+59 is! To
find out, we type
GOTO 10
remembering to use letter Oh's (not digit zeros) in
GOTO.
This tells the VIC to execute the command
labelled "1 0". It does so, and the answer finally
appears. You can do this as many times as you
like. It does not destroy a command to have it
listed or executed.
The VIC can remember many commands at
the same time. (The limit is set by the size of the
memory: it takes one byte to hold each character
in a command, plus a little bit of overhead for
the command as a whole.) Every command must
have its own label in front of it, and all the labels
must be different. The machine always stores
and lists commands in increasing order of label,
and obeys them in this order too unless it is
commanded not to.
Try typing NEW
10 PRINT "FIRST LINE"
20A=5
30B=10
40 PRINT A;B;A+B
50 STOP
Remember to end each command with
Now try a LIST, and then a GOTO 1 0, and
check that trie results are those which you expect.
The STOP will make the VIC stop and display a
READY when it reaches the end of the sequence
of commands.
The sequence in which commands are stored
is kept right even if you type them in a different
order from their label numbers. For instance, if
you had typed:
30 B=10
10 PRINT "FIRST LINE"
40 PRINT A;B;A+B
50 STOP
20A=5
these five commands would still have been listed
and obeyed in the order 1 0, 20, 30, 40, 50. Clear
the machine with a NEW, and try it for yourself.
Always start by making numbers go up in
steps of 1 0. If you decide later to slide some extra
commands in between the others, this rule makes
it much easier: you can then use intermediate
label numbers such as 1 5 or 38.
Why bother storing commands at all? There
are two good reasons:
• Commands which are fetched out from the
VIC's own internal memory are executed
much faster than if they are typed in.
• Commands which have been typed in once
... can be obeyed many times over. Practically
every useful job done by a computer involves
repetition, and it is only sensible to put the
commands into the computer's memory,
where they are easy and fast to get at.
. Perhaps the easiest way to get repetition is to
store a labelled GOTO command. Consider the
following program:
10 PRINT "NORTH"
20 PRINT "WEST"
30 PRINT "SOUTH"
40 PRINT "EAST"
50 GOTO 10
When it is started at label 10, the VIC obeys
the first four commands in sequence. The next
command sends it back to label 1 0, so that it starts
the sequence all over again. It just keeps going
roun d and round, and only stops when you type
mill or turn the machine off.
Now clear the machine and type in the
program. Start it by giving the initial command
GOTO 10
You will see the machine obeying the lines of your
program, much faster than you can read them.
You can slow the machine down by pressing and
holding HHl^B ( try it) , or you can stop it in the
usual way with the UU! key.
At this point, we will actually show the
advantage of using label numbers separated by
1 0. Suppose you want to alter your program so
that it includes the diagonal directions
NORTH
NORTH-WEST
WEST
SOUTH-WEST
etc.
You need four new instructions in between
the existing ones. If you number them 1 5, 25, 35
and 45 they will go in just the right places. Type
the following:
15 PRINT "NORTH-WEST"
25 PRINT "SOUTH-WEST"
35 PRINT "SOUTH-EAST" ;
45 PRINT "NORTH-EAST" '■":}.■'
• . Now LIST -your program, and check thajyour
new lines have been inserted between tfaebla ;
ones, in the right places* Run the;„prog,ram:0nd •
see' What happens.'- ^v ; - ; ' ;
Now write and test your own program on the
some lines.. If ydu use graphics charocfers in the
strings instead of letters, you can get some ' 1
irt^ii^iftoj^|9)rn.s brt'i^''!^r<wi ; ^,V' J '
-'.I The' GQtO 1 command you have been
using to start your program has a more con-
venient equivalent: RUN. RUN simply makes the
VIC start obeying commands at the one with the
lowest number.
When you put a semicolon after a string, the
VIC doesn't take a new line between that string
and the next one when it runs your program (but
of course you must still end each command with '
the return key). Instead, it starts a new line across
the screen on ly when it reaches the right-hand
edge. A simple program like the one below will
quickly fill the whole screen with curious designs;
try it, and explain its action.
10 PRINT"!— It- 1 - i 1 L- ";
20 GOTO 10
Experiment 5. 1 Completed
EXPERIMENT
5-2
33
A sequence of commands which is repeated
over and over again is called a loop. Aloop may
include many different sorts of commands,
including a LET, which gives a new value to a
variable. Look at this program, and try to predict
its action:
10 LET A = 1
20 PRINT A
30LETA=A+1
40 GOTO 20
Pretend you are the computer and do exactly
what the computer does, patiently, step by step.
Write down what happens to the variable A and
its values. Don't read on until you have thought
hard and filled in your answer.
(and so on)
Now enter the program and run it; holding
down the
key to slow it down. (But don't
Until you have typed
touch I
afterRUN.;
I'm sure you found this problem quite easy,
but here is an explanation of what you saw.
The program begins by obeying the com-
mand labelled 10, which gives the variable A the
value 1 .The next command displays this value on
thescreen.
Command '30' replaces A by A+ 1 . This is the
same as adding 1 to the qld value of A, so the
result (this time) is 2. The next command is a
GOTO, and makes the VIC return to command
20! The value of A is displayed again, but now it is
2. The machine again works through the sequence
20, 30, 40 and again, and again, but each time
round the value of A is increased by 1 . This gives
the sequence 1 ,2,3 . . .
To give you some practice, try predicting the
first few lines displayed by these two programs
(remember, # means "times"):
10B=0
20 PRINT B
30 B = B+3
40 GOTO 20
10A=T
20B = A*A
30 PRINT A,B
40A=A+1
50 GOTO 20
And now check to see if you were right.
You can do the same kind of thing with
strings. Try this program:
10X$ = "★"
20 PRINT X$
30X$ = X$ + 'W"
40 GOTO 20
The successive values of X$ as the program
goes round the loop will be *,
*•###, and so on. The string X$ gets longer and
longer, and uses up more space on the screen
each time it is printed. After some 40 seconds, the
string gets so long that it won't fit in the machine's
memory (the largest number of characters
allowed is 255), and the machine reports a fault:
? STRING TOO LONG
ERROR IN 30
The line ERROR in 30 means that the
command which tried to store the offending string
was the one labelled 30.
Here are some more programs for you to
predict.
10A$ = "++"
20 PRINT A$
30 A$ ="A"+A$+"— '
40 GOTO 20
10A$ = "XY"
20 PRINT A$
30 A$ = A$+A$
40 GOTO 20
Remember that if a letter comes inside a
string, it is just a letter and not a variable name.
So "X" has nothing to do with variable X or X$.
As a final exercise, write a program with a
simple loop, and run it for exactly one minute,
timing it with your watch. Then stop it, see how far
it has gone, and calculate how many commands
the machine has obeyed in the time. Reduce your
figure to the number of commands per second,
and write your answer here:
Experiment 5.2 Completed
The self-test quiz for this unit is called
UNIT5QUIZ.
u
u
u
□
u
u
u
□
u
u
u
u
□
□
□
u
□
LJ
u
□
u
u
□
□
□
□
u
□
u
u
u
u
u
u
UNIT:6
EXPERIMENT 61
PAGE 37
EXPERIMENT 6-2
38
EXPERIMENT 6 3
40
EXPERIMENT 6-4
42
The purpose of this whole course is to help
you learn how to design and build your own
programs. To back up your growing knowledge
of programming you will need a collection of
techniques or "tools" to organise your work, and
to help in putting things right if they go wrong.
This unit is a tool kit and puncture outfit. It isn't
about programming as such, but the contents will
be useful in an emergency. Read the unit
carefully, get to know the techniques it describes,
and give it a permanent place in your mind as you
go further into the course.
EXPERIMENT
61
Load and run the Unit 6 program, called
SENTENCES. Take a look at the 'random'
sentences it displays. These absurd statements
are constructed by a form of internal 'conse-
quences', where each word or phrase is selected
by chance from a short list of possibles. Here we
shan't worry about how the program works
(although it is quite simple in principle) but we'll
use it as an example in showing you how to list,
alter and preserve large programs.
When you have seen e noug h of the sentences,
stop the program with the t£E9 key, and do a
LIST. The program is far too long to fit on the
screen, and as the listing runs most of it disappears
from the top of the frame. At the end, only the last
six commands can be seen.
The BASIC language includes some special
versions of the LIST command to allow for this
situation. There are five possibilities, which you
should try out as you read about them:
• You can list the whole program by typing LIST.
This, as is now clear to you, has certain draw-
backs if the program is too long.
• You can list a selected command by giving its
number. For example
LIST 11 00
will display command 1 100 (and no other).
• You can list all the commands up to a given
label number by putting a — sign in front of the
number. Thus
LIST — 80
shows all the commands from the beginning
of the program up to the one labelled 80.
• You can ask for all the commands from a
given label number up to the end of the
program by putting a - sign afrerthe number:
LIST 9090-
• Finally you can list all the commands between
any two numbers by quoting both numbers:
LIST 2000 — 2090
Now use some of these types of LIST com-
mand to look at various parts of the program.
You will quickly notice that the label numbers
don't always go up in steps of 1 0; this is because
the program was altered manytimes afteritwas
first written.
At the head of the program and in several
other places you will see commands with the key-
word REM, followed by descriptive statements in
English. REM is short for "remark". These lines
play no part in the program itself, but are included
to make the program easier for people to read.
When you begin to write complicated programs
you should always use plenty of REM's to explain
what you are doing.
When you are satisfied that you have fully
understood the various forms of the LIST
command, try some experiments to see what
happens if:
(a) The command you refer to isn't there .
(try LIST 650)
(b) The label numbers are in the wrong order.
(try LIST 110 0—1000)
(c) The LIST command is included in a program.
Type NEW, then type in this program and run
it.
10 PRINT "LIST TRIAL"
20 LIST
30 GOTO 10
Experiment 6. 1 Completed
EXPERIMENT
This experiment discusses how programs
can be altered and modified. At present you will
be making changes to a program originally
written by someone else, but later most modifica-
tions you make will be to your own programs.
There are three kinds of change you can
make to a program:
(a) Removing existing commands
(b) Adding new commands
(c) Amending or replacing existing commands.
Removing Existing Commands
There are five ways to get rid of a labelled
command in VIC's store, but three of them involve
deleting or changing the entire program and are
quite drastic in their effect.
A whole program can be deleted by
• Switching the VIC off
or • Typing NEW
or # Loading a new program from cassette
tape or disk.
An individual command can be removed
• By typing its label number alone
• By typing another command with the
same label number.
Reload the SENTENCES program and delete
a few lines which have the REM keyword. Check
that the deletion has worked by LISTing an
appropriate part of the program both before and
after.
Adding New Commands
A new command can be added to a program
by typing it, with a suitable label number. The
command is inserted at the place determined by
the label number.
We have already practised inserting com-
mands in UnitS, but you can take this opportunity
to insert a few REM commands. Make sure you
don't replace any existing statement, or the
program won't work.
Altering Existing Commands
The most drastic way of altering a command
is to retype it, using the same label number.
Let's try an alteration. Begin by replacing the
copyright line (label 5) with a line containing your
own name. The dialogue might go:
►LIST 5
5 REM COPYRIGHT © ANDREW
COLIN 1981
You type-»-5 REM CHRIS BLOGGS
'-•►LISTS
5 REM CHRIS BLOGGS
Try altering a few more lines, but keep to
those with REM keywords, otherwise you will
almost certainly damage the program and
prevent it from working properly. A program is
like a living cell; random mutations are nearly
always bad and usually fatal.
When a line needs only a minor change, it is
often easier to alter the original (which is already
on the screen) than to type a new version. This is
done with the cursor and possibly with the I
key. When the changes are complete, the
key will make the VIC register the
new command in place of the old.
Suppose you want to alter line 1 00, so that it
reads
1 00 REM MAIN STUPID SENTENCE GENERATOR
LIST command 1 00, put the cursor on the S of
SENTENCE, and insert 7 blanks (use I
and W3M ). Then type the wo rd STUPID, c heck
.Do
that all is correct, and strike
another LIST 1 00 as a check.
Try a few more alterations of this type,
always keeping to REM comman ds. Remember
if you don't strike ^mm^B a ft er
changing a line with the cursor, the machine .
won't register your changes!
Now type RUN at the end of the program. If it
doesn't work any more, you must have made a
mistake in editing, such as erasing or altering a
statement without noticing. Don't be upset— this
is quite common. Just reload the program from
the cassette tape.
You must have observed that the SEN-
TENCES program makes statements about well-
known figures. The lists of possible choices are
very short: they are in commands 9070 (for men)
and 91 00 (for ladies). For the final part of this
experiment you are invited to alter these lists so
that the program makes up sentences about your
family and friends instead.
Each of the two commands 9070 and 91 00
has the keyword DATA. This is followed by the list
of names, separated by commas. The last name is
followed by a comma and the letter Z .*
There can be as many names as you like. If
the names run to more than 4 lines, use a second
DATA command (with a label number one up on
the first one). Third and fourth commands can
also be used. Only the last DATA command in
each group needs the Z at the end.
Some possible alternatives for lines 9070
and 91 00 could be:
9070DATABILL,GEOFFREY,
PERCIVAL,MR.SOPHOCLES,
THE HEADMASTERS
91 00DATAGRANNY,SUSAN,V
IOLET,MRS.PINKERTON,TH
E GYM MISTRESSAUNTIE
FLO,RACHEL,PENNY
91 01 DATAKATE,LAURA,FRA
NCES,NORAH,Z
When you've made these changes, run the
program again. If it comes up with complete
nonsense check that you have put a comma
between each name (but not two commas) and
that the last name is followed by a Z.
Once you've got the feel of making changes,
you can apply your imagination to the other lists
of words in the program. They are:
9000 Actions that people do by themselves
(intransitive verbs)
901 Actions that people do with each other
(transitive verbs)
9020 Actions that people do with clothes (transi-
tive verbs)
9030 Items worn by men
9040 Items worn by ladies
*The use of Z at the end of a DATA command is a
feature of this program only, not of BASIC in
general. DATA commands in most other pro-
grams don't need the Z at the end.
EXPERIMENT
6-3
9050 A list of adverbs and adverbial phrases,
describing actions that people do with
each Other.
9060 A list of adverbs and adverbial phrases,
describing actions that people do by them-
selves
9070 Men's names
9080 Adjectives describing men
9090 Various sorts of men
9100 Ladies' names
9110 Adjectives describing ladies
91 20 Various sorts of ladies
Alter the lists in any way you like. Remember
to keep them consistent. . If you alter 9020 to
actions dealing with food, you must alter 9030
and 9040 accordingly, otherwise you may get
sentences like
SUSAN ATE HER WELLINGTON BOOTS
If your lists are very much longer than the
originals, there is a danger of running out of
space. The VIC uses its memory both to store the
lists of names and as a 'scratchpad' for internal
calculations. The overall capacity is 3583 bytes,
and this is quite easy to exceed. In the extreme
case, the machine will report an error as you
actually enter a statement, but the computer can
also run out while it is making up new sentences.
The cure is to make the lists snorter.
Experiment 6.2 Completed
When you have altered the SENTENCES
program to say amusing things about your
friends, you may want to keep the new version to
show at parties, etc. This section explains how to
preserve the program on a cassette tape.
Get hola of a blank tape, or one with nothing
on it that you need to keep. It should be of good
quality, and as short as possible: you are only
going to use up about one minute's worth of tape,
and mere is no point in paying for more. The
special cassettes made by Commodore are ideal.
Load the new tape into the cassette unit in
place of the SENTENCES cassette, and rewind it.
Release all the keys on the cassette unit. Then stop
the SENTENCES program, and type
SAVE "FAMILY"
(you can use any name you like instead of
FAMILY).
The machine replies
PRESS RECORD AND PLAY ON TAPE
Follow these instructions, pressing both keys
on the recorder at the same time.
If the RECORD key won't go down, check
that the tape you are using hasn't had its 'write
permif tabs taken away. These tabs are at the
back of the cassette, like this:
TABS
If the tabs are broken off, it is impossible to
put any new material on the tape. The idea is to
protect important recordings which mustn't be
destroyed, so get yourself another tape.
If all is well, the machine says
SAVING FAMILY
and a moment later,
READY.
In theory, your program is now recorded, but
it is better to check. Various things may have gone
wrong: you may have forgotten to rewind the
tape, or to press the RECORD button, or the tape
itself could have a small bald patch which
prevents it from making a correct copy of the
program. These things shouldn't happen, but in
practice they do!
To check your tape, re wind it, and the n type
VERIFY "FAMILY"
The machine replies
PRESS PLAY ON TAPE
Press the PLAY button (but not RECORD this
time). The machine then looks for your program
on the tape, and checks it against what is in the
memory. Naturally you mustn't make any altera-
tions between the SAVE and VERIFY commands.
If all is well, the messages you will see are:
If the machine finds an error, or doesn't get
as far as FOUND FAMILY, you must go back to
the beginning and try the SAVE command all over
again. If the trouble persists, try another tape (or
the other side of the first one). If you still can't
make the system work, take the VIC and the
cassette unit back to your dealer for a check-out.
Once a program has been SAVE'd, it can be
stored away and LOAD'ed at any time, with a
command such as
LOAD "FAMILY"
A program doesn't need to be perfect to be
SAVE'd. If you are writing a very long program
(or even copying one from a book) it pays to
SAVE your work every half-hour or so. This is
because the VIC memory isn't as reliable as a
tape in a drawer. The machine itself is unlikely to
break down, but other accidents can happen.
Thunder storms have been known to corrupt the
information in a computer store: there may be a
power cut, or your baby sister can trip over the
mains lead and jerk the plug out of the wall. If you
lose six hours of work through such an incident,
you may feel a little upset. If you have been taking
regular half-hourly dumps you can reload the
most recent version and go on with only a small
loss of your time.
To make the system absolutely safe, you
should SAVE on two different tapes alternately.
Then even if the machine stops during a SAVE,
with half the old version obliterated by half of the
new one, you are still protected.
It is amusing to play a VIC program tape
through an ordinary (sound) recorder.
Experiment 6.3 Completed
i !
EXPERIMENT
6-4
In this section we point out a subtle and
dangerous trap which lies in wait for VIC
programmers, and tell you how to clamber out if
you do fall in.
To begin, we'll try to drop you straight in to a
simple example of the trap. Type NEW to clear
the store, ana then enter the following program,
inserting all the spaces shown carefully, and
watching the screen as you type.
1
P
R
1
N
T
A
G
R
E
A
T
T
R
A
P
2
G
O
T
1
Now do a LIST and check the program, which
should appear exactly as shown.
You would expect the program, when typing
RUN, to display the message
A GREAT TRAP
over and over again until it is stopped. Try it and
see. It is likely to come up with
A GREAT TRAP 20
? SYNTAX
ERROR IN 10
READY.
Even if your program does work correctly,
read on ana find out just why you managed to
avoid the pitfall.
The reason the machine failed to run your
program (assuming that is what it did) is by no
means obvious. You could show the program to
the world's greatest experts on BASIC, and they
wouldn't see anything wrong with it.
The difficulty arises because of the screen
width of the VIC. Inside the machine, any BASIC
command may be up to 88 characters long. The
screen is only 22 characters wide, so the
displayed version of a command can spread
over anything up to 4 screen lines.
When you type a command and the cursor
reaches the end of a screen line, the system
moves it on to the beginning of the next line; but it
still assumes that you are typing the same
command. A command is only ended by the
key.
If you fell into the trap (as you were supposed
to), here is what happened:
You type the first command (which was care-
fully designed to fill up the who/eof a screen line).
You then found the cursor at the beginning of the
next line and naturally typed the next command,
Since you didn't
ending it with a
endthefirstlinewitha ^mggm^B , the system
thought that both lines were part of the same
command, namely
1 PRINT "A GREAT TRAP" 20 GOTO 1
This "command" is not correct BASIC, and
gives rise to a syntax error when the machine tries
to execute it.
This type of error is particularly difficult to find
unless you know what you are looking for. You
are most unlikely to notice the mistake as you type
the program — even experienced programmers
often forget to end their commands with
HUH! if the cursor is at the beginning of
a new line. If you LIST the program, or even the
section which includes the error, the faulty
command looks exactly like two correct ones,
and the fault is invisible.
Fortunately, the error can be pinpointed by
LIST'ing just the command in which the error is
reported. If you type LIST 1 0, out come lines 1
and — apparently — 20! This must be wrong,
since you only asked for 1 0. To correct the
trouble, retype both commands completely,
remembering to end each one with I
In summary:
(a) Always end e very command with
HHUI , no matter where the cursor
may be.
(b) If the VIC reports an error in a command and
you can't see anything wrong with it, LIST it
out by itself and check whether it runs on into
the next command in the program.
Experiment 6.4 Completed
u
u
u
□
u
u
u
□
u
u
u
u
□
□
□
u
□
LJ
u
□
u
u
□
□
□
□
u
□
u
u
u
u
u
u
The programs we wrote in Unit 5 were
undisciplined. Once they were started, itneeded
drastic action to stop them arid most, if left to
themselves, would have gone on arid on for ever.
This unit is about how tb control programs, and '
ma ke them stop when they have gone far enough. 1
. . The topics described in this unit are funda-
mental to computing. When you master them, you
take the biggest single step towards being a ; .
programmer. Read the unit slowly and carefully*
anaif you are in any doubt' about some point, go
back and read.about it again. Jt is welLworth .
doing because these ideas, once you understand ;
them, will take you a long way forward.
The control of programs depends on a key
concept, which may benewtoyou: the condition.
When people talk, they mostly make
statements which are true, or which are at least
supposed to be taken as true:
"My train broke down on the way in."
"I love you."
A condition is a special kind of statement
which is not necessarily true, but might equally
well be false. In English we use conditions after
the word 'if. In the following sentences the
conditions are printed in bold type:
"If the last train has left, you'll have to
spend the night in Aviemore."
"If the program doesn't work, find the
fault and fix it."
The speakers of these sentences are not
insisting that the last train has gone, or that the
Erogram really doesn't work; they simply don't
now, and are making plans accordingly. In
English, a condition can turn out to be true or
false, without the speaker being called a liar.
In BASIC, conditions also come after the
keyword IF. They involve the various 'objects'
used in programs: number variables, string vari-
ables, numbers and strings. The conditions, which
can be either true or false in any instance, are
built round one of six relationships. This is best
illustrated by example:
Consider the BASIC condition:
A<5
(where < is a sign which means "is less than").
This condition is true if the va I ue of the variable A
really is less than 5 (say or 3 or 4.98). It is false if
A is worth 5 or more.
Another example, this time using strings, is
N$o"JIM"
(where <> means "is different from").
This condition is true if the variable N$ has
any value except "JIM"; thus it is true if
N$="JACK" or N$="JIMMY". It is only false if
N$ actually is "JIM".
The full set of relationships you can use in
BASIC are these:
—
(is the same as)
<
(is less than)
>
(is more than)
<>
(is different from)
<=
(is not more than)
>=
(is not less than)
The relationships <>, <= and >= are each
typed with two key depressions. These symbols
may be more familiar to you in the forms ¥=, ^
and but the designers of BASIC had to accept
the fact that computer keyboards don't usually
have keys marked with these signs.
The relationships can all be used either
between pairs of numbers, or between pairs of
strings to make conditions. Numbers and strings
can be represented by appropriate variables.
Thus
5> 4 is true because 5 is greater than 4
7 <=6 is false because 7 is more than 6
ifA = 10andB = 7,
A >=B is true, and so is B<= 7.
When relationships are used between strings
they imply alphabetical (dictionary) order, so that
"DOG" > "CAT" is true,
and "JIM" > "JIMMY" is false.
EXPERIMENT
7-1
Suppose that the computer has obeyed the
following three statements:
LETA$ = "JOAN"
LETX = 5
LETY = 7
Work down the following table, and mark
each condition as false or true:
Condition
Value (false or true)
X<7
X>=5
A$<>"X"
YoX
A$ < "FRANCES"
A$>"JOAN"
Y = 8
The quantities on either side of the relation-
ship can be expressions, just as in LET
commands. The expressions can be as complex
as you wish, but the important thing is to compare
like with like: a condition which had a number on
one side and a string on the other would make the
VIC stop and report a fault.
Assume the values of A$, X and Y are the same
as above, and work out each of the following
conditions:
Condition
Value (true.or false)
A$+"NE"o"JOANNE"
5>X
X + Y<>13
X+2=Y f
• Now check your answers, which are given in
Appendix B.
Experiment?.! Completed
EXPERIMENT
The chief instrument of control in BASIC is the
IF command. It consists of the keyword IF, a
condition, the word THEN, and a label number. It
is very like a GOTO, but with one difference: the
jump only happens if the condition is true.
An example of an IF command is
IF X$ <> "ABBBB" THEN 20
Here the condition is X$ <> "ABBBB" and
the whole command tells the machine to jump to
20 if X$ is different from "ABBBB". If this condition
is false, the machine continues obeying com-
mands in their numerical order.
If you are like most people, your first reaction
to this command is that it is a bit absurd. "Either
X$ is different from that string with the A and B's"
you say, "Or it isn't. It all depends on what comes
before, but in any case when the programmer
wrote that IF command, he must have known!"
Your view is understandable, plausible, but
wrong. There could be two entirely different
reasons:
• Suppose the IF command is in a loop where
some variable has its value changed every
time round. The condition could well be true
for some of the values, but not others.
• Supposeagainthatyouarewritinga program
for someone else to use. Then you won't know
in advance what the user is going to do with it,
but the actions of the program must still
depend on what he or she actually does. If you
want a good example, the author had to make
the various quiz programs respond in a
sensible way to your answers even though he
had no idea how you were going to reply to
any of the questions.
Putting an IF statement in a loop gives a good
way of stopping it when it has gone round enough
times. Type in and run the following: '
: i0X$="A" ? iy- \ :;^X :
. 20 print x$ ■ . \ V : •
30 X$=X$ + "B" :', .-'
40 GOTO 20
50 STOP
This program runs on, filling the screen with
ever-lengthening strings of B's until it runs out of
space. The STOP at line 50 is never reached.
Now stop it and replace line 40 with
40 IF X$ <> "ABBBB" THEN 20
When you run it, it displays
A
AB
ABB
ABBB
and stops!
The reason lies in the condition
X$ <> "ABBBB". As the program goes round
and round the loop, the condition is at first true
(because X$ is AB, and then ABB, and then ABBB,
all of which are different from ABBBB). In each of
these cases the IF command behaves like a
simple GOTO 20 and sends the machine round
the loop another time. Eventually, X$ gets to
ABBBB. The condition is now false; the jump
doesn't happen and the machine drops through
to the end of the program where it stops.
Now try altering the condition in various
ways, and observe the effect when you run the
program. Whatever string you use, make sure
that the condition eventually becomes false,
otherwise the program will never stop.
Possible conditions to try are:
X$o"AB"
X$< >"ABBBBBBBBBBB"
X$<"ABBA"
The same control technique can be used with
numerical variables.
Type in 10P =
20 PRINT P,P*P
30 P=P+1
40 GOTO 20
50 STOP
Run this program, see what it does, stop it,
and change line 40 to read
40IFP<11THEN20
Now run the program again. It displays two
columns of figures which look familiar, and could
be useful to someone who didn't know the
squares of the numbers by heart. As a working
program there is only one thing wrong: the
display isn't labelled, and its meaning is not
immediately obvious to anyone but you.
We can fix this defect by adding a heading,
or line at the top which identifies each column,
like this:
NUM SQUARE
1 1
2 4
3 9
etc.
Clearly the heading has to be displayed
before any of the numbers or squares, so the
command which displays it must come first. Since
label 1 is already used, and it would be pointless
to change all the labels in the whole program, a
sensible decision would be to use label 5. The
command itself is a PRINT, with two strings:
"NUM" and "SQUARE". The comma between
the strings ensures that the spacing corresponds
to the spacing between the columns of figures.
The whole program now reads:
5 PRINT "NUM","SQUARE"
10P=0.
20 PRINT P,P*P
30 P=P+1
40IFP<11THEN20
50 STOP
Run the program in this form, and examine
the output.
Do you want a blank line between the head-
ing and the first row of figures? The command
PRINT by itself (without any value or string to
follow) will give you an empty line, so try adding
the command
7 PRINT
In a few minutes you will be asked to write
some programs of your own. Before you start,
let's take a careful look at the programs we have
already run, and draw some general
conclusions. The example programs are:
0)
10X$="A"
20 PRINT X$
30 X$=X$+"B"
40 IF X$ <>"ABBBB" THEN 20
50 STOP
(2)
5 PRINT "NUM'V'SQUARE"
7 PRINT
10 P=0
20 PRINT P,P*P
30 P=P+1
40 IF P< 11 THEN 20
50 STOP
If we forget about the heading commands (5
and 7) in the second program, both programs
seem to follow a set pattern. In each case,
1 . There is a variable which changes regularly
as the loop is repeated. You'll see that it is X$
in the first program and P in the second. In
general, this is called a control variable, and it
can be either a string or a number.
2. There is a command which gives the control
variable its starting value. This command is
outside the loop (that is, it is not repeated but
only obeyed once).
3. There is a command which is obeyed for every
value of the control variable. In our examples,
these are the PRINT commands
PRINT X$
and PRINT P,P*P
In practice, this part of the loop can be
expanded to include any number of com-
mands, all of which are obeyed for each value
of the control variable. This group is called the
body of the loop.
4. There is an increment or quantity by which the
control variable grows each time round the
loop. In our examples, X$ grows by adding a
"B", and P is increased by 1 . Other increments
are possible; for instance a string could grow
by 5 symbols at a time, or a number could go
up in steps of 2 or any other number. It could
also start with a high value and go down.
The loop always includes a command which
moves the control variable one step further
each time it is obeyed.
5. There is a final value for the control variable.
When the loop has been executed with this
value, the repetition must cease. The last
command in the loop is an IF command, with a
condition which is true if the loop is still due to
be executed, but false when the control
variable has passed its final value.
In the table which follows, examine each
program and fill in the name of the control
variable, the starting value, the final value, the
increment and the number of times the loop is
obeyed. To work this out, it often helps to jot
down the value of the controlled variable on the
first, second, third ... . time through the loop, and
to see how many values there are until the final
value is reached.
Control
variable
Starting
value
Final
value
Increment
No. of
times
round
loop
10X$="A"
20 PRINT X$
30 X$=X$+"B"
40 IF X$o"ABBBB"THEN 20
50 STOP
X$
"A"
"ABBB"
"B"
4
10P=0
20 PRINT P,P*P
30 P=P+P
40IFP<11THEN20
50 STOP
P
10
+1
11
10Y$="Z"
20 PRINT Y$
30Y$=Y$+"XY"
40 IF Y$ <>"ZXYXYXY"THEN 20
010 o 1 \Jr
10R=5
20 PRINT R,R/8
30 R=R+3
40IFR<17THEN20
D\3 o 1 vJr
10C=27
20 H=30-C
30 PRINT C,H
40 C=C-5
50IFC>2THEN20
60 STOP
EXPERIMENT
7-3
When you have completed the table, check
your answers against those given in the back of
the book (Appendix B).
Experiment 7.2 Completed
When you construct a program, you should
begin by doing some design, and then writing out
the whole program on a piece of paper. Use
pencil and rubbed Some people compose their
programs directly on the computer keyboard, but
this method is only for geniuses or morons — it is
definitely not recommended for ordinary people.
The reason is quite plain: if you start without
plans you have about as much chance of success
as a builder who puts up a house without any
drawings, making up the architecture as he goes
along. He might just produce an architectural
jewel, but he is much more likely to end up with a
leaky hovel which will blow open at the first storm.
When you design a loop for a program, you
have to decide all the essential items for yourself.
They include the name and type of the controlled
variable, the starting and ending values, the
increment, and the details of the body of the loop.
When you have made up your mind on these
points, you can put them together in the standard
pattern.
Here is a worked example.
One pound sterling (£1 ) is worth 2350 Italian
Lire at today's rate of exchange. We need a table
which gives the Italian equivalent of Sterling
amounts from £5 to £75, going up in steps of £5.
The display is to start:
£ LIRE
5 11750
10 23500
and so on.
Let's think about the loop first. The control
variable will clearly be a number, and we can
call it PS (this stands for "Pounds Sterling" and is
as good as any other name). The starting value
wilfbe 5, the final value 75, and the increment 5.
The body of the loop is to print a value in £'s, and
the corresponding value in Lire, which is 2350
times more.
The elements of our loop can now be jotted
down. They are:
PS=5 < ■ - -. ■
PRiNTPS,2350*PS «-
(Sets initial value)
PS=PS+5«-
(Increments PS)
IF PS<80THEN <«- } (Checks iffinal value passed)
STOP — - — - — — j (Stops program)
The label number following THEN is left blank
because we don't know what it is going to be.
Before writing down the whole program, we
should consider the heading. Suitable commands
would be:
PRINT "£", "LIRE"
and PRINT 4-
(To get a blank line)
Now we can assemble the parts and write
out the whole program:
10 PRINT "£","LIRE"
20 PRINT
30PS=5
40PRINTPS,2350*PS
50 PS=PS+5
60 IF PS < 80 THEN 40
70 STOP
At the risk of becoming boring, let me
repeat; oW* short cut the design process: don't
improvise your program straight into the
computer. If you do, you'll never make a good
programmer.
Now try these examples:
1 . Write a program which displays a pattern of
stars, thus:
★
★★★
up to
★★★★★★★★★★
Write a program which gives the equivalent
of$US for sums of British money between
£1 and £30, going up in Steps of £2.
(Take £1 =$1.77).
The relationship between the Fahrenheit and
centigrade scales is expressed by this
formula
F = 1.8*C + 32
Write a program which tabulates Fahrenheit
equivalents of Centigrade temperatures
between 1 5° and 30°, going up in steps of 1 °.
(HINT: the body of your program could be
F = 1.8*C + 32
PRINT C,F
This has implications for your choice of name
for the controlled variable.)
When you have written and run all these
programs, check your solutions against those in
Appendix B.
Experiment 7.3 Completed
People who like school Mathematics and are
good at it sometimes get confused by the way that
the "=" sign is used in BASIC If this doesn't apply
to you, you can safely skip this section.
In Mathematics, "=" is used in equations, to
assert that two different expressions really have
the same value. The equation tells you something
which is true. For instance, if the Maths teacher
writes on the board
"2x + 5 = 9"
you can be sure that for the particular x the
teacher has in mind, the statement is right. If this
weren't so, you can imagine the following
conversation:
Pupil puts hand up.
Teacher: Yes?
Pupil :xistwo
Teacher: No. The answer is seventy eight
Pupil :Eh? I don't understand.
Teacher: I lied when I said 2x + 5 = 9!
In BASIC "=" is used in two different senses,
neither of which is the same as the mathematical
one.
In a LET command, the sign means
"becomes". It's an instruction to calculate the
vdlue of the expression on the right, and to put this
value into the variable on the left. Instructions
aren't statements, and it doesn't make sense to
say that they are, or aren't true. (They may be
wrong in a particular context, but that is a
different matter.) The trouble is that if LET is left
off, the command looks like an equation. It isn't.
Let's make this clear:
In BASIC
Y=X+2
doesn't inform the computer that Y equals X+2; it
orders it to work out the value of X+2 and put the
result in variable Y. Here are some points to
ponder:
Q=Q+5
• P=Q)
and Q=P J
X+1=5
is a reasonable and useful
BASIC command
Are not the same in their
effects
isnofa legal BASIC
command
In each case do you see why? Try to explain it
to yourself in your own words.
The other use of "=" is in conditions. You'll
remember that = is one of six possible relation-
ships between quantities. Examples of its use are
IFX=Y+2THEN100
IFN$="YES"THEN150
Again, there is no implication that the condi-
tion actually is true; instead the command is an
order to work out whether the condition is true,
and to take certain action if it is. In conditions "="
has the same logical force as any other relation-
ship such as < or >=. It is best to avoid the word
"equals" and to call the symbol "is the same as".
To summarise:
BASIC uses "=" in LET commands, where it means
"becomes", and in conditions where it means "is
the same as", but what it says isn't necessarily
true. Got it?
The self-test program for this unit is
UNIT7QUIZ.
called
At this point in the VIC course you are just
beginning to write your Own programs. The first
ones are short and simple. Later, as you develop
your knowledge, experience and skill, you are'
certairi to design and'write programs of ever
greater complexity and interest. The table gives
you some idea of how far you can go:
Program
Number of
Commands
Converting Italian Lire to
£ Sterling (Unit 7)
7
Unit 3 quiz program
about 100
Chess playing program
about 5000
Program to control an
industrial robot
about 25000
Program which runs a
computerised airline
booking system
about 5000000
Naturally, any program with more than
about 5000 commands is always the result of a
team effort (it would take too long for one person
to write) but there is stil I plenty of scope for the
individual programmer.
As you work at programming, you will often
find yourself stuck. A program you have just
written and keyed in with great care simply
doesn't do what you expect. This unit describes
some of the ways you can get over this difficulty.
Read it now, and do the exercises; but remember
that you can always refer back to it again when
(not if) the need arises.
When people come to their first program-
ming difficulty, they react in different ways. Some
feel angry and insulted; some immediately give
up in despair, and decide that programming is
not for them; and some pretend that the program
is "ninety nine percent right" and go on to the next
problem! None of these reactions makes good
sense. The only thing to do is to find the mistake
and put it right. It can be a great comfort to
remember that every programmer sometimes
gets stuck, even those who have been working
with computers for 25 years.
Program errors fall into three groups. The
first and most common type is the one which
comes up with SYNTAX ERROR when the
computer tries to obey a particular command.
This means that the command doesn't follow the
rules of the BASIC language. For instance, it might
have a spelling mistake in a keyword, or there
may be too many (or too few) double quote signs.
Most syntax errors are caused by typing mistakes
and are obvious once you know they are there;
but Appendix C gives a checklist of the kind of
error to look for if you are in difficulty.
The second type of program error arises
when the VIC finds a particular command impos-
sible to obey. Suppose the machine came to the
command
130 GOTO 500
but there was no command labelled 500. This
would make the machine stop and display an
error message:
UNDEFINED STATEMENT IN 1 30
Unfortunately the error messages tend to be
in programmer's jargon rather than plain English,
but they are fully explained in Appendix C.
The third sort of program fault is the most
difficult of all to find and put right. There are no
error messages; instead, the computer simply
displays the wrong answer to your problem or
bogs down in a loop without displaying anything
at all. The first and most obvious thing to do is to
stop the machine, LIST the program and examine
it carefully. This will usually help you pin-point the
error. However, suppose it doesn't; let's imagine
that you have spent a good few minutes
examining each command, and you still can't find
anything wrong.
At this stage you need a more powerful
method of investigating the workings of your
program. The method is called 'program tracing'
and consists of pretending that you are the
computer. You start at the beginning of the
program and work through it, command by
command, until you get a sudden insight into the
cause of the trouble. You will need to be patient
and methodical, and above all you'll need to
switch off your intelligence, and work through the
set of instructions like a stupid robot, without
trying to make "plausible guesses", generalisa-
tions, or use any other type of short cut.
To imitate the computer, you must first have a
good idea of how it works. Suppose you could
somehow "freeze" the VIC between two com-
mands in the middle of running a program, open
it up and look inside. You would discover*:
First, the program itself, stored in the memory
in much the same form as it was originally typed.
Second, the variables the program has used
up to this point. Each variable occupies some
room in the memory, and has a value, which
could be a number or a string.
Third, you find that the computer has kept
track of its place in the program. Somewhere
(actually, in a special variable called the
"program pointer") it remembers the label
number of the next command it is due to execute.
Now let's unfreeze the computer just a little,
long enough for it to execute one command. The
command the machine chooses will naturally be
*lf you tookthe cover off the VICyou wouldn't
actually see these things, but only a few silicon
chips and other components. However, me
appropriate electronic instruments would
certainly show you the items we mention.
the one remembered by the program pointer.
When you look again, there will be certain
changes, and they depend on the command
which has just been obeyed. Here are some of the
possibilities:
(a) a PRINT command will make something
appear on the screen.
(b) a LET command will create a new variable if
one is needed, and put a new value into it.
Both the PRINT and the LET commands will
also move the program pointer on to the next
command in sequence, so that when the
computer is restarted it 'knows' which
command to obey next.
(c) a GOTO will not display anything or alter
any variables. It will simply reset the program
pointer so that it indicates the command men-
tioned in the GOTO. For example, the
command
130 GOTO 270
will put 270 in the program pointer.
(d) the IF command works in the same way,
except that the condition is worked outfirst. If
it is true, the program counter is set, just like in
a GOTO. If it is false, the program counter is
simply moved on to the label of the next
command in sequence.
Look at: 120 IF X = 5 THEN 170
130 PRINT "NO"
If X does have the value 5, the condition is
true, and the program counter is changed to
1 70. Otherwise, if X has some other va lue, the
program counter is simply advanced to 1 30.
(e) the STOP command indicates that the pro-
gram has ended, by displaying a BREAK
message. There is no point in continuing the
program beyond this point.
To imitate the computer accurately, you'll
need to see all these parts clearly: the program,
the variables, the display and the program
counter. A good method is to use a "program
trace chart" which you draw on a piece of paper.
Arrange it like this:
PROGRAM POINTER 10
VARIABLES
DISPLAY
PROGRAM
10A=5
20PRINT"ALPHA=";A
30A=A*3
40 B=A+37
50 PRINT "BETA=";B
60 STOP
The program you plan to trace is filled in on
the right, and the starting value of the program
pointer — that is, the label number of the first
command to be obeyed — is at the top. Make
sure that the program is an exact copy of the one
which is giving you trouble: if it isn't, your trace
will be a waste of time.
Now you are ready to start. The program
counter says '1 0', so take and interpret the com-
mand labelled '1 0'. It says A=5, so it must be a LET
command. Look in the box marked VARIABLES
for an A. There isn't one, so write down an "A", a
colon and the value 5. Finally, move the program
pointer on to the next command in sequence,
putting a line through the previous value:
PROGRAM POINTER 20
VARIABLES A: 5
DISPLAY
PROGRAM
10A=5
20PRINT"ALPHA=";A
30A=A*3
40 B=B+37
50 PRINT "BETA=";B
60 STOP
The next command is interpreted in the same
way. You forget the 'purpose' of the program, or
any knowledge you may have about sequencing,
and take command 20 only because the program
pointer says so. The command is a PRINT, and
you can work out that it will display "ALPHA = 5".
Put this down in the DISPLAY section, and
advance the program counter, giving:
PROGRAM COUNTER -J0--30- 30
VARIABLES A: 5
DISPLAY
PROGRAM
ALPHA = 5
10A=5
20PRINT"ALPHA=";A
30 A=A*3
40 B=A+37
50 PRINT "BETA=";B
60 STOP
The next command gives a new value to an
existing variable A. You first work out the expres-
sion A*3 using the old value (5) and record it,
crossing the old value out, like this:
A-S-15
The command after that creates a new vari-
able. Continue tracing until you reach STOP. The
final result is:
PROGRAM COUNTER 40-.S0-.30-.40--50-60
VARIABLES A: -5-15
B: 52
DISPLAY
PROGRAM
ALPHA = 5
10A=5
BETA = 52
20PRINT"ALPHA=";A
BREAK IN 60
30 A=A*3
READY.
40 B=A+37
50 PRINT "BETA=";B
60 STOP
The next example involves a simple loop:
10 P=l
20 PRINT P; P*P*P
30 P=P+1
40 IF P<4 THEN 20
50 STOP
The trace of this program as far as line 30 is
straightforward:
PROGRAM COUNTER -*0--30--30-40
VARIABLES P:-f-2
DISPLAY
PROGRAM
1 1
10P=1
20 PRINT P; P*P*P
30 P=P+1
40 IF P<4 THEN 20
50 STOP
The next command at 40 is an IF. To imitate
the computer, evaluate the condition P<4. Since
the current value of P is 2 (that's what it says in the
VARIABLES section), and 2 is clearly less than 4,
the condition is true. All you do, therefore is to put
20 as the new value of the program counter. You
get
PROGRAM COUNTER W2$r2ffiM' 20
VARIABLES ?-.Jr7
DISPLAY
PROGRAM
1 1
10P=1
20 PRINT P; P*P*P
30 P=P+1
40IFP<4THEN 20
50 STOP
The trace continues this way, until at last the
condition is false, and the program reaches
STOP. The final result is:
PROGRAM COUNTER W2Qr3frM'20-3&'
A?r2Sr3firJfir 50
VARIABLES P: +^8-4
DISPLAY
PROGRAM
1 1
10 P=l
2 8
20 PRINT P; P*P*P
3 27
30 P=P+1
BREAK IN 50
40 IF P<4 THEN 20
READY.
50 STOP
EXPERIMENT
81
Now practice your tracing with the following
programs. Use a pencil, and nave a rubber
nanay in case you make a mistake:
(a)
PROGRAM COUNTER 10
VARIABLES
DISPLAY
PROGRAM
10X=5
20Y=7
30Z=X+Y
40W=Y-X
50 PRINT X;Y;Z;W
60 STOP
(b)
PROGRAM COUNTER 10
VARIABLES
DISPLAY
PROGRAM
10Q=1
20 PRINT "SHE LOVES
ME"
30 PRINT "SHE LOVES
ME NOT"
40Q=Q+1
50 IF Q<3 THEN 30
60 STOP
When you have completed these two
experiments check your answers against those
given in Appendix B.
Experiment 8. 1 Completed
EXPERIMENT
8-2
How can tracing be used to find mistakes? It
depends on switching between a state of robot
obedience, and a state of human intelligence.
First you become a robot and trace a command
exactly as the computer would have executed it.
Then you go back to being a person, and ask, "Is
this what I expected?" If so, you carry on the
trace. If not, you will have a good clue as to why
the program is going wrong.
Here is a simple example. Suppose you've
written a program to display the 1 2 times table.
The display you expect is
TWELVE TIMES TABLE
1 ★ 12 = 12
2*12 = 24
3*12 = 36
(and so on down to)
12*12 = 144
Your program has all the right parts: a loop,
a command to display a heading, and a PRINT
command to display each line of the table. It
reads:
1 PRINT "TWELVE TIMES TABLE"
20 P=l
30P=P+1
40 IF P< 13 THEN 30
50 PRINT P; "*12="; P*12
60 STOP
When you run this program, the results are a
bit disappointing. All you get is
TWELVE TIMES TABLE
13*12 = 156
BREAK IN 60
READY
Not what you expected! The mistake may be
perfectly obvious, but let's pretend you can't spot
it. You begin to trace, and after a few steps you
get
PROGRAM COUNTER WZflrltirMrlRrM' 30
VARIABLES P.- -+c3»3-4
DISPLAY
PROGRAM
TWELVE TIMES TABLE
10 PRINT "TWELVE TIMES TABLE"
20 P=l
30 P=P+1
40 IF P< 13 THEN 30
50 PRINT P; "*12="; P*12
60 STOP
and you suddenly realise that the value of P is
working its way up to 1 2 without anything being
displayed. It is now clear that the PRINT command
ought to be inside the loop, not outside. The right
place is between commands 20 and 30. The IF
command also needs to be changed to jump
back to the PRINT. A quick edit produces
10 PRINT "TWELVE TIMES TABLE"
20P=1
25 PRINT P; "★12="; P*12
30 P=P+1
40 IF P< 13 THEN 25
60 STOP
Program tracing is an extremely useful tech-
nique if you have the patience to do it step by step.
If you make guesses about whole sections of
program, you are likely to make the same
mistake as you did when you wrote the program
in the first place, and the trace won't reveal your
error.
There are a few circumstances under which
the tracing method as described doesn't work,
and you should know what they are:
• If a program is very large, a straightforward
trace would just take too long. More appro-
priate methods will be described later on in
the course, at the time you may actually need
them.
• If you simply don't bel ieve that you can ma ke
a mistake, then tracing won't be much help.
Most people, when they write down the last
line of a program, experience a strong moral
certainty that 'This time it's right". The feeling
only comes because you haven't been
conscious of making any mistakes, and is
extremely misleading. It is much betterto say
to yourself "This time it's wrong. Let'sfindthe
mistakes". But you'll need to swallow your
pride!
• If you have misunderstood some fundamental
aspect of BASIC, a trace will again be of little
help. To take a crude example, imagine
someone who believes, firmly but mistakenly,
that in BASIC the sign " — " means
"addition". He writes a program to add two
numbers like this:
10A=34
20B=19
30 PRINT"A=";A
40 PRINT "B=";B
50 PRINT "A PLUS B ="; A— B
60 STOP
When he runs this program, it displays
A = 34
B = 19
APLUSB = 15
BREAK IN 60
READY
which is clearly wrong. On the other hand,
when he traces it, he finds that command 50
gives
A PLUS B = 53
which is what he expects. As long as he really
believes that " — " means "add", he will
never find the error!
Of course most misunderstandings are much
more subtle than this one. Nevertheless, if your
trace comes out differently from the result dis-
played by the VIC, and keeps coming out differ-
ently when you repeat the trace, this is clear
evidence that there is something about the art of
programming you haven't understood correctly.
If you can, get advice from someone who knows
BASIC better than you do*; but otherwise go back
to the beginning of the text-book, and check
every single item of your knowledge against
what it says. This will nearly always bring the fault
to light.
Sometimes — very very rarely— your difficulty
may be caused by a mechanical fault in the com-
puter. Modern machines like the VIC are extremely
robust and reliable, and when they do break
down, it is usually obvious: the cursor won't come
up when you switch on, or you find it impossible
to load programs from your cassette recorder. In
practice you should never blame the computer
for not running your program until you have
examined every other possibility two or three
times over. When you send your machine to be
repaired, you must explain exactly why you think
it is broken, and include a copy of the program
which it refuses to run correctly.
*There are now plenty of people who understand
BASIC. If you aon't mow anyone personally, an
advertisement in a local shop window will
usually find help.
Here are two programs with mistakes for
you to find and correct.
(a) This program is supposed to display a con-
version table for gallons to litres, starting at 1
gallon and ending at 10 gallons (1 gallon =
4.5 litres)
1 PRINT "GALLONS", "LITRES"
20G=1
30 PRINT G,4.5*G
40G=G+1
50IFO11THEN30
60 STOP
(b) This program is supposed to be a solution to
problem 1 in Unit 7, to display a triangle of
stars. It was actually written by someone
learning BASIC:
10A$ = "*"
20 PRINT A$
30 A$ =
40 IFA$o"*********"THEN20
50 STOP
Experiment 8.2 Completed
EXPERIMENT
8-3
The program on tape UNIT8PROG is sup-
posed to display the 7-times table, but contains
several errors. Load it, find and correct the
mistakes. Check your answers in Appendix B.
Experiment 8.3 Completed
EXPERIMENT
91
Let's draw some more pictures. This time,
we'll make the VIC do all the hard work and
drudgery for us.
It you think back to units 2 and 3 (look to
remind yourself if you like) you'll remember that
when you draw on the screen you can use a
number of control 'functions':
• Cursor movement in four different directions
• Selection of eight different colours
• Colour and background reversal (on and off)
• Moving the cursor 'home' to the top of the
left-hand corner
• Clearing the screen.
These functions share keys on the keyboard,
so that you often have to use'
to choose the function you really need.
You won't have forgotten that you can set the
frame and background colours using a 'POKE'
instruction and a code number from the table on
page 1 7.
The VIC can also make drawings on the
screen under the control of a program. Every
program has the use of all the screen control
functions: it can select any colour for its charac-
ters, it can clear the screen whenever it needs to,
and it can move its own cursor (which is invisible
to you) to any position using the cursor control
functions.
Of course the VIC only does these things
when obeying the commands you have given it.
To put screen control functions into a command is
easy: we simply include them in strings alongside
the other characters to be displayed. You might
find this a bit puzzling at first. Surely, if you type a
string and include a screen-clearfunction in it, the
whole screen will disappear as you type? In fact
this does not happen, as the next experiment is
designed to show.
Do you remember that in Unit 2 we said,
"Don't use the double quotes, they're funnyl"
Now you are going to find out what effect they
really have, and why they're so useful.
When you start typing a command (say after
a READY or a H^^H ) the VIC is in
'normal' mode. Control functions like colour
selection or cursor movement work in the way
you have come to expect. As soon as you type a
double quote character to mark the beginning of
a string, the machine changes to quote mode.
Ordinary characters such as letters or graphics
are still treated in the normal way, but control
functions are not obeyed: instead they are put
into the string as 'special' characters, mostly
letters, signs or graphics on a reversed back-
ground. The machine switches back to normal
mode when you type a second double quotes
character (so ending the string) or if you give a
Start up the VIC, type a double quote and
then give all the control functions, one by one.
See how each one looks on the screen, and fill in
the table below.
Function
KeyStnjck
Symbol displayed
Clear Screen
HCLR
HOME
Cursor home
Cursor up
and
Cursor down
Cursor left
SHIFT |H|CHSR
Cursor right
Black
and
White
and
Red
and
Cyan
and
Purple
and
Green
Blue
and
and
Yellow
and
Reverse on
and m
Reverse off
and
Now let's try some of these controls in action.
First make sure your TV set is properly adjusted
for colour, by using the TESTCARD program if
need be.
Next get the computer to display the word
"EDINBURGH" in yellow. Type in the command
PRINT'
> hold down )
EDINBURGH
What actually appears on the screen (all still
in blue) is
PRINT
EDINBURGH". The reversed it
symbol is the code for "yellow".
Now hit the mgfm^p key. The word
EDINBURGH appears on the screen, in yellow.
This experiment illustrates the principle quite
clearly: when a control function is typed inside a
string, it is not put into effect when it is typed, but
only obeyed when that string is displayed by the
computer.
You will see that the flashing cursor has been
left yellow. Change it to black or blue, whichever
you prefer, by typing the correct control function
— without quotes.
A PRINT command which gives you a colour
change can be made part of a program, just like
any other command. Key in and run the
following:
GLASGOW"
INVERNESS"
10 PRINT"
CTRL
andHHSk
20 PRINT"
CTRL
andlESL
30 PRINT"
CTRL
h -
and IB
and
40 STOP
ANDREWS"
Command 30 shows that you can put more
than one control function into a string.
Screen and cursor control functions can also
be put into strings. Type the following:
PRINT "I
<=
CRSR
CRSR
r> .
CTRL
1 and
u C „ L i I CRSR I CRSR I CRSR I CR? H
H0ME| o 1 -U- 1 -U- 1 =>
PARIS"
On the screen this comes up as
PRINT " ^AwimMMm^ PARIS'
When you strike ^mjfjjjj^p / the CO ntrol
functions are actually obeyed. The screen is
cleared, the cursor is moved three places down
and three along, and the word PARIS appears in
red half-way towards the middle of the screen.
Try it for yourself.
In general, you can get the VIC to paint
words and symbols anywhere you like by
including the right number of cursor shifts in a
string.
When you get the computer to draw a picture
on the screen, you don't want to spoil everything
SHIFT
and
CLR
HOME
-TV
CRSR
•U-
o
CRSR
by displaying READY and the flashing cursor. A
way out of this difficulty is to use a 'loop stop', or a
GOTO which jumps to itself. Once the computer
reaches this command, it will start chasing its own
tail, and it won't display READY until someone
hits the ytii key. This program, for example,
will display LONDON in white in the centre of a
black screen: , n .
1 times
1 POKE 36879,8 — — 1
20 PRINT
i LONDON'
8 times
30 GOTO 30
Key this program in, run it, and then stop it
with the Willi key. The screen will still be
black and the cursor white, but you can quickly
get back to the normal state of affairs by holding
down ESS and hitting HHNM . In fact,
you can always do this if the machine gets stuck
for any reason; it is better than switching on and
off because your program isn't lost when you do
it.
As a short exercise, get the VIC to display
words and patterns of different colours at various
positions on the screen. Remember that the
and US function clears the screen,
so if your program has a sequence of PRINT
statements, only the first one should begin with
this function — although some of the others could
well start with K5 by itself.
Experiment 9. 1 completed
EXPERIMENT
9-2
You will know that modern clocks and
watches are controlled by quartz crystals, and
are extremely accurate over long periods of time.
The VIC also incorporates a quartz crystal
vibrating several million times every second, and
it is used — among other purposes — to control
an internal digital clock. This clock doesn't have
its own dial; instead, it is treated just like a string
variable, so that you can display the time on the
screen whenever you need. The name of the clock
variable is Tl$.
When you first start up any clock, you have to
set it to the right time. The VIC is no exception. You
can ad just the clock from the keyboard, by typing
a command like
Tl$ = "193746"
This would set the clock to 7.37 and 46
seconds in the evening.
If you want to set the clock very accurately, it
is best to wait for — say — the nine o'clock news
on the radio. Just before it starts type
Tl$ = "090000"
as you hear the last
and then hit
'pip' of the time signal.
Once the VIC's clock has been adjusted, it
wil I keep time, to within a few seconds a day, until
the machine is switched off. There is no need for
you to reset it or to change it from within a
program.
To display the time, you simply mention Tl$ in
a PRINT command.
Now set up the VIC's clock, using your own
watch (it doesn't matter if the setting isn't very
accurate). Then display the value of Tl$ several
times, using a PRINT command. See how the
seconds change from one time to the next.
Now display the time continuously, by
running the program
10 PRINT Tl$
20 GOTO 10
Stop this program, wait a few minutes, and
restart it. You will see that the time is still correct,
and that the clock has been running all the time.
This method of displaying the time is not
attractive. You can make the VIC into a respect-
able digital clock by a program as follows:
command 10: Selects a purple frame with yellow
background
command 20: Clears the screen
command 30: Moves the machine's cursor home,
then down 9 lines and across 6
spaces; no newline needed
command 40: Displays Tl$
command 50: Jumps back to command 30.
Write down the code for this program in the
box below; then enter it on the VIC keyboard and
try it out. If you get really stuck, look up the correct
version in Appendix B, but don't go on until you
have studied it carefully and found out how it
works.
Experiment 9.2 Completed
EXPERIMENT
9-3
Controlled loops are often useful in drawing
shapes on the screen. Suppose you want a 1 x 1
block of red dots in the top left-hand corner. This
can be done by displaying ten lines, each with ten
• graphics: .
10 PRINT'
20J=1
30 PRINT
• ••
40J=J+1
50IFJ<11THEN 30
60 GOTO 60
This program combines several of the ideas
we have already met in previous units. The semi-
colon at the end of command 1 prevents the
machine from starting a new line after clearing
the screen, so that the first line of red dots
appears at the top. Statements 20 to 50 form a
controlled loop and 60 is a loop stop.
Enter the program and run it as it stands.
Then stop it, and try for yourself the effects of
(a) removing the semicolon after " BEGS "
(b) changing the 1 1 in command 50 to some
other value (say 1 5)
(c) removing command 60
You can of course make these changes by LIST'ing
and editing. Remember to get the cursor colour
back to blue or black before you start!
To get a solid block of colour we use
reversed spaces. Try changing line 30 to
land
and run the program again.
What happens if we want more than one
block of colour in the same picture? The trick is to
move the machine's cursor to the first line of the
area, and then to fill it in, without interfering with
the colour already on the screen. We'll look at
two examples:
(a) To paint a blue 10x10 block just below the
redone:
The lower half of the screen is empty, so we
don't need to worry about spoiling anything
else. Furthermore, after drawing the red
block, the cursor will be in the right place. We
can extend the program by adding
60J=1
70 PRINT
1 CTRL
land 139V
CTRL
L
and
1 spaces — *
80J=J+1
90IFJ<11THEN70
100 GOTO 100
Notice that the loop stop has been moved to
the end of the program where it belongs. J is
used as control variable in both the red and
blue loops: this is perfectly alright because
the red block is completely finished before
the blue one is started, ana J isn 'tasked to do
two jobs at the same time.
(b) To paint a 1 x 1 black block beside the red
one.
The starting line is the top one, so in drawing
the black area we have to be careful not to
damage the red block which is a I ready there.
This can be done by moving the cursor home,
and displaying 1 lines, each of which begins
with 1 "cursor right" movements to jump
over the red. The program extension is
100 PRINT'
110J=1
1 times
120 PRINT "
<=.
CRSR
C=
CRSR
CTRL
and £3!1
CTBL
and
- 10 spaces -*
130J=J+1
140 IFJ <11 THEN120
150 GOTO 150
Now assemble this program, type it in and
try it out. Note that it has three separate loops
which are executed one after the other.
Try extending the program to put a purple
block under the black one. . .
As a final exercise, try writing programs to
display some simple flags, or other patterns
which fill the whole screen. You will need your
wits about you, because various pitfalls lie in
wait.
• The normal meaning of a semicolon at the
end of a PRINT command is "Don't start a
new line". If the VIC is made to put a charac-
ter into the right-most position of a line, it
automatically moves its cursor to a new line.
Displays which are meant to fill complete
lines should therefore be followed by
semicolons unless you actually want a blank
line to follow.
# There is no way of using a PRINT command
to write a character into the lower right-hand
corner of the screen without making the
whole screen move up.
The way to get this square the right colour is
to select the entire background colour
accordingly.
You should plan your painting carefully,
using squared paper as a guide. When you come
to write your programs, be prepared to make
plenty of mistakes, and don't be upset if it takes
several tries to get things right. Remember that
you learn by success — not by failure — so don't
just give up!
To start you off, we'll give you a program for
the French flag.
We'll make the central white stripe 8 charac-
ters wide, and the other two 7 each. 7 + 8 + 7 = 22.
Appropriate starting colours are a red
background and a black frame.
We can build up the flag by displaying 23
lines, each with seven white squares and eight
blue ones. Remember that the last one must be
different, because it mustn't be followed by a
new line. We can put the first 22 lines into a
controlled loop, but the last will need a com-
mand on its own.
We arrive at
10 POKE 36 879,40
20 PRINT'
30J=1
40 PRINT " ■DM and
• 7 spaces
- 8 spaces
50J=J+1
60IFJ<23 THEN40
70 PRINT "^BBand
- 7 spaces -
- 8 spaces
80 GOTO 80
Run this program and study it carefully until
you understand every symbol. Now try some of
your own flags, but keep off from ones with
diagonal elements! Try the Iceland flag which is
shown on page 1 9. You can check your answer
with the one shown in Appendix B.
Experiment 9.3 Completed
The self-test program for this unit is called
UNIT9QUIZ.
u
u
u
□
u
u
u
□
u
u
u
u
□
□
□
u
□
LJ
u
□
u
u
□
□
□
□
u
□
u
u
u
u
u
u
In the previous units we came across the idea
that commands can be written once, but obeyed
many times over. This happens whenever you put
a command in a loop.
On a much larger scale, a similar thing
occurs with complete programs. Most programs
are designed to be useful, which means that they
are stored and distributed on tapes or ROM-
packs and used many times by different people. If
you want an example, look at the various taped
programs which form part of this course.
Let's begin by considering all the programs
which you personally have written so far. The
drawback with everyone of them is that no matter
how many times you run it, it always produces the
same result. Hardly very useful!
To give a specific example, let's go back to
the program which calculates and displays a
conversion table between £UK and Italian Lire. It
was:
10 PRINT "£", "LIRE"
20 PRINT
30 PS=5
40 PRINT PS, 2350*PS
50 PS=PS+5
60IFPS<80THEN40
70 STOP
On the day the Unit was written, the rate of
exchange really was 2350 Lire to the Pound, so
the program would have given correct results. By
today, however, the rate has fallen to 21 75. Any
bank which used this original program to sell Lire
in exchange for Pounds would be seriously out of
pocket.
How could matters be improved? If you are
a programmer one obvious approach would be
to alter line 40 to read
40 PRINTPS,2175*PS
Unfortunately this idea won't take you very far.
Most people who use computers aren't program-
mers, or even if they are, they are just not interested
in the guts of your program!
To make programs more flexible, more
adaptable to everyday needs, we need a new
facility: one which lets the user supply information
which the programmer couldn't have known
when the program was written. A program which
allows this can be used by lots of different people,
and lets each one solve their own particular
version of a problem. For instance, suppose that
the money conversion program allowed the user
to tell it the current rate of exchange every time it
was used; it would immediately become useful to
banks all over the world, and it would work
properly for any imaginable exchange rate.
Suppose you are designing a program for
someone else to use. You beoin by deciding which
quantities you are going to ve undefined, and
your program is going to ask the userto supply. In
our example the rate of exchange is clearly one
such quantity: it must be unknown to the pro-
grammer, but known to the user! You allocate the
unknown quantities to variables, and give them
names accordingly. For instance, a suitable name
for the rate of exchange could be RE. You can
then write your program using symbolic names
instead of the actual values (which you cannot
know in advance). Thus line 40 of the exchange
program could read
40 PRINT PS, RE*PS
Of course there is something missing from
this description. You may not know the values of
the variables, but the machine must do so when it
runs your program. The command which lets the
user put in the missing information has the key-
word INPUT. This is followed by the name (or
names) of the variables needed. When the INPUT
command is obeyed it waits for the userto type a
value, which it then stores in the named variable.
The rest of the program, which uses this variable,
can now be obeyed.
Before giving an example, we stress one vital
point: every program with an INPUT command
must tell the user exactly what is wanted of him.
This can usually be done with PRINT statements.
his information, it was actually obeying the INPUT
command.
The INPUT command comes in several
slightly different forms. We'll look at some
examples, and mention a few general rules.
1 . Clear the VIC by typing NEW, and type in
Study the following program carefully:
3 PRINT 'TYPE TODAY'S"
4 PRINT "RATE OF EXCHANGE"
5 PRINT "BETWEEN £ AND LIRE"
6 INPUT RE
10 PRINT "£","LIRE"
20 PRINT
30 PS=5
40 PRINT PS, RE*PS
50 PS=PS+5
60 IF PS<80THEN40
70 STOP
Notice how the program doesn't assume any
particular rate of exchange, but uses the variable
RE to represent it wherever it is needed. The
program begins by telling the user what is needed
and asking him to supply a value.
Enter the program, check it carefully, and
type RUN. Now pretend you are a user: a money-
changer who knows nothing about program-
ming. On the screen the machine is asking you to
type something, so you enter the appropriate
figure, and then strike the HmmEI key.
As soon as you do this, the screen fills with a
conversion table that lets you start business today.
Run the program many times, and notice
how well it can handle different rates of
exchange. Even if the Lira were to be revalued to
a level of 23.7 to the £, the program would still
produce sensible answers.
Now switch back to your personality as pro-
grammer. When the program was running,
showing a cursor ana waiting for the user to type
1 PRINT "WHAT'S YOUR NAME"
20 INPUT N$
30 PRINT "HELLO I
"; N$;"!'
Run this program and see what happens. The
example shows how the INPUT command
works with strings as well as numbers. You
could use this sequence — or something like
it — near the beginning of any program
where you wanted the computer to be
'friendly' to the user. If the program was a
quiz of some kind, you could use the value of
N$ in commands like
40 PRINT "NO^Br'; N$ ; ". YOU
CAN DO BETTER THAN THAT"
(If you are in any doubt about what this
command displays, tack it on to the end of
the program already in the VIC, and run the
program again.)
2. Try
10*NPUT"NAME";N$
20 PRINT "GOODBYE I
This example shows how a short piece of
descriptive information can be included in
the INPUT command itself. The information
shows up on the screen as a guide to the user,
just before the?.
Command 1 in the example is equivalent to
the sequence
PRINT "NAME";
INPUT N$
Notice that the string of descriptive words
must be less than 22 characters long, and
that it must be followed by a semicolon.
3. Lastly, try
1 PRINT "GIVE TWO NUMBERS TO
BE ADDED"
20 INPUT A,B
30 PRINT "SUM=";A+B
40 STOP
The INPUT command now expects two
values, and the user must type th em separated
by a comma or by pressing the!
Dy a comma or oy pressing melMi
key. (That is, he or she could type either -
say 43, 19
or
43
19
In general, the INPUT command may ask the
user for any number of variables, but it is better to
75 keep the number down to two to prevent confu-
sion. In the command itself, the names of the
variables are separated by commas.
When you have run this program a few times,
pretend you are a really stupid user and try typing
nonsense — for example
DONALD,DUCK
The computer will accept anything at all as a
string, but if it is trying to input a number, and is
given something which couldn't possibly be a
number, it will display the message
REDO FROM START
and give you another try.
Sometimes you want to stop a program when
it is obeying an INPUT command and displaying
a cursor. Under these conditions the 61111 key by
itse lf is disab led. You must hold it down and strike
the mum k e y a t the right of the main
keyboard. Try it!
Experiment 10.1 Completed
EXPERIMENT
10-2
Writing useful programs is easy provided
you remember that the programmer and the user
are two different people. The user can't be
assumed to understand programming (so he
cannot be expected to LIST your program to find
out what it does). In general the programmer may
not 'talk to' the user except by making the VIC
d isplay messages on its screen, and the user can't
get back to the programmer at all, so the
program had better not leave any questions
unanswered!
When you are designing a program, pretend
you are a fly on the wall watching someone trying
to use it. Try to imagine everything that could go
wrong, and prevent it by making sure the
program gives the user plenty of guidance.
When your program is written, you can
exercise it by pretending you are a user; later, as
a final test, bribe a friend or relative to be a
'guinea-pig' and to try the program out for you. If
your guinea-pig has to ask you any questions
about what to do, or what the answers displayed
actually mean, your test has failed and you
should redesign your program accordingly.
Write programs to do the following jobs:
(a) To display any multiplication table selected
by the user.
(b) To ask the user (who is assumed to be a
married man) for his surname, and then for
his wife's Christian name; and then to display
his wife's full name.
Solutions are given in Appendix B, but don't
look at them until you have done everything you
can to write these programs by yourself.
Experiment 10.2 Completed
The quiz for this Unit is called UNIT1 OQUIZ.
u
u
u
□
u
u
u
□
u
u
u
u
□
□
□
u
□
LJ
u
□
u
u
□
□
□
□
u
□
u
u
u
u
u
u
UNITrll
EXPERIMENT 11 1 PAGE 79
EXPERIMENT 11 -2 83
EXPERIMENT 11 -3 89
One of the most interesting features of
programming is its richness and variety. The
same computer, if properly programmed, can be
made to serve as a calculator, a teaching
machine, a musical instrument, a monitor to look
after a sick patient in hospital, or almost anything
else useful you can think of. This power comes
from the huge number of ways that a few basic
types of command can be put together.
So far, our total vocabulary of commands
used within programs is only seven:
PRINT, LET, GOTO, IF, INPUT, STOP and POKE
Of course there are other BASIC commands you
still have to learn about; but in this unit we'll
explore the potential of the commands we
already know.
The most flexible command of all is the IF. In
previous units it's been used to control loops, but
it is also useful in many other ways. For instance it
can test data or items of information supplied by
the user, so as to steer the computer along the
right course of action.
EXPERIMENT
hi
Let's imagine you are setting up a computer-
ised marriage bureau, and the first facility you
plan to provide is a program to advise on the
ages of the partners your customers should look
for. By tradition a man should marry a girl of half
his age, plus seven. This implies, if you think
about it, that a girl should look for a husband who
is double her age, less 1 4.
Clearly, the advising program must begin by
asking for the client's age. Then, to give the right
advice, it has to find out whether the client is a
man or woman. The program will be used both by
men and women, so it must include a separate
group of commands to give advice to each of the
two sexes. Finally there must be an IF command
to select the group actually needed on a
particular occasion.
A first version of the advising program is
given below. Study it carefully and work out
exactly why each command is included:
10 INPUT "WHAT IS YOUR AGE";AG
20 INPUT "MALE OR FEMALE";SX$
30 IF SX$="MALE" THEN 70
40 PRINT "YOU SHOULD LOOK FOR"
50 PRINT "AMAN OF";2*AG-14
60 STOP
70 PRINT "YOU MUST FIND" .
80 PRINT "A GIRL AGED"; AG/2+7
90 STOP
You will have spotted that the variable AG is
used to hold the client's age, and SX$ his (or her)
sex. The condition SX$="MALE" is true if the
client answers MALE to the question "MALE OR
FEMALE?". The expression AG/2+7 is BASIC'S
way of saying "half your age plus seven", and
2*AG— 1 4 means "twice your age less fourteen".
When you have looked at the program, test
your understanding by predicting as accurately
as you can what will appear on the screen (a) for
a man of 20, and (b) for a girl of 22. Use the boxes
below. The first box is partly filled in for you.
RUN
WHAT IS YOUR AGE? 20
MALE OR FEMALE?
(a)
Now enter the program into the VIC. Try it out,
on behalf of various sorts of client, and check that
both your predictions are right.
This simple example shows you that the
action of the computer needn't be fixed in advance
by the programmer, but can be made to depend
on the information supplied by the user.
Programs often have complicated sets of
decisions to make, so to plan them we use a
special type of diagram called a flow chart. The
flow chart for the advising program is like this:
80
INPUT AGE
INPUT SEX
DISPLAY: "YOU
TRUE
MUST FIND A
GIRL AGED
< <
Vi AGE + 7"
FALSE
DISPLAY: "YOU
SHOULD LOOK FOR
> >
A MAN OF
2* AGE —14"
81
A flow chart consists of a number of blocks
connected by arrowed lines;There are four kinds
of blocks:
(a) A square or rectangular box. The box holds .
the description of a simple action, which can
later be translated into one or two BASIC
commands. In our sample flow chart, the top
two blocks are examples of this type. The
arrowed lines show that the program starts
by obeying the first block, and then goes on
to the second one, in that order.
(b) A diamond holds a condition, which may be
either true or false. The diamond has one line
going into it, but two coming out, labelled
TRUE and FALSE (or sometimes YES and
NO). The diamond corresponds to an IF
command. It instructs the computer to test the
condition, and to follow either the TRUE or
the FALSE line according to the result.
(c) The terminal block, which tells the computer
to stop obeying the program. It is a small
circle with the word STOP.
(d) The cloud (which doesn't appear in our
example). This is a symbol for an action
which is too complicated to be described in
detail. Usually, the cloud can be expanded
into another complete flow chart, just as a
country-wide road map is backed up by
detailed plans of different towns.
A flow chart is really a 'map' of a program. A
computer running a program is a little like some-
one playing a board game. At the beginning the
player's token (motor-car, top hat or whatever)
goes oh the first block. Whenever the action
described in a block has been completed, the
token is moved along the arrowed line to the next
block.
Wheh the token lands oh a diamond, the
player looks at the condition and decides whether
it is true. If it is, then he moves his tokeri fo the box
at the end of the TRUE line, but otherwise, he
follows the FALSE line. Eventually he reaches a
STOP block, which is the end of the game.
The point of this illustration is to help you see
two very important things about computers:
• A computer can do only one thing at a time
(not several)
• The order in which the computer does things
is determined by the program.
It often surprises people that there is no flow
chart symbol for a simple GOTO command. This
is because the GOTO doesn't specify any action
at al l; it only affects the order in which commands
are obeyed. It is well represented by a connecting
line. For instance:
10Q=1
20 PRINT Q; Q*Q
30Q=Q+1
40 GOTO 20
has the flow chart
i
LETQ = 1
DISPLAY Q
AND Q 2
ADD 1 TO Q
Now draw a flow chart for the following
program. Use the plastic stencil for your blocks:
10S=1
20 PRINT S,12*S
30S=S+1
40 IF S< 13 THEN 20
50 STOP
(Check your answer in Appendix B.)
Experiment 11.1 Completed
EXPERIMENT
11-2
g
Tl
83
DISPLAY: "YOU
TRUE
MUST FIND A
GIRL AGED
< <
y 2 AGE + 7"
i
r
Let's do some more exploring. One feature of
our marriage guidance program was that if you
live it incorrect data, it gives you silly answers,
he name for this fact is "GIGO", which stands
for "Garbage In, Garbage Out". For instance, a
girl who gave her age as 6 would be told to find a
husband aged -2: not even a gleam in his r
parents' eyes! Furthermore, if the user gives any
answer other than MALE to the second question,
the program assumes she is female. Someone
who repl ies "M" or "MAN" or. "MASCULINE" Or
"BOY" will be told to find a man as partner.
There are plenty of programs which do:
behave in this idiotic way, and they have given
computing something of a bad reputation. In
Cractice you can avoid the worst of these troubles
y passing the user's information through a filter
to make sure that it is at least sensible.
To begin with, we'll draw a new flow chart
for the whole program, replacing the detailed
input boxes with a cloud:
FALSE
DISPLAY: "YOU
> »
SHOULD LOOK FOR
A MAN OF
2* AGE -
-14"
We use a cloud because we haven't yet fixed :
the details of what we actually mean by
"sensible". The cloud is useful because it allows
us to plan the program as a whole unit, but it
involves an obligation to work out the action in
greater detail. At the stage we have reached now
the planning is not complete, but that doesn't
mean that the main flow chart is useless or wrong!;
Well, what does "sensible" mean? First let's
think about the age of the user. The lowest likely
value is 1 8, because people under 1 8 don't often
come to marriage bureaux. The upper limit is
harder to decide, but according to the Guinness ■
Book of Records the oldest living person is 1 1 5.
We'll take this figure as a guide,
"- - • Well design+he program so that when the
computer asks for the client's age, it decides
whether to accept ifcas reasonable. If not, it
displays a reason, and invites the client to give a
more realistic figure. Look at this flow chart:
INPUT AGE
When it comes to the second question, there
are lots of ways the client could indicate whether
they're male or female. In fact there are so many
that we could never think of them all. Instead we'll
make the program "understand" only two
words: MALE and FEMALE. If the reply is given in
any other way, the program will ask for it to be
repeated. The correct bit of flow chart is
DISPLAY "YOU ARE
TOO YOUNG TO
GET MARRIED"
84
DISPLAY "I DONT
BELIEVE YOU"
i r TRUE
INPUT SEX
TRUE
H
DISPLAY "YOU MUST
ANSWER MALE OR
FEMALE"
Now we can put these two fragments
together to give a complete flow chart for the
cloud which is to get sensible values for AG and
SX$.
INPUT AGE
FALSE
DISPLAY "YOU ARE
TOO YOUNG TO
GET MARRIED"
FALSE
DISPLAY "I DONT
BELIEVE YOU"
INPUT SEX
TRUE
Once,a set of flow charts has been carefully
drawn, translating them into a program is a
straightforward job. We start at the main flow
chart, but the first block there is a cloud, so we
refer to the subsidiary flow chart and translate it.
Then we go back to the main chart for the rest of
the program.
You will notice that two of the diamonds in
the subsidiary chart have a TRUE line which goes
DISPLAY "YOU MUST
ANSWER MALE OR
FEMALE"
straight to the end. The simplest way of filling in
labefnumbers of the corresponding IF command
is to put a REM at the end of the cloud and use its
labernumber. The REM does nothing but act as a
convenient anchor point:
We get:
10 INPUT"WHAT IS YOUR AGE"; AG
20IFAG>=18THEN50
30 PRINT "YOU ARE TOO YOUNG TO BE
MARRIED"
40 GOTO 10
50IFAG<=115THEN 80
60 PRINT "I DONT BELIEVE YOU!"
70 GOTO 10
80 INPUT "MALE OR FEMALE"; SX$
90 IF SX$="MALE"THEN 130
1 00 IF SX$="FEMALE" THEN 130
1 1 PRINT'YOU MUST SAY MALE OR FEMALE"
120 GOTO 80
1 30 REM AG AND SX$ HAVE SENSIBLE VALUES
This is followed by the rest of the program as
before (but with adjusted label numbers).
140 IF SX$="MALE" THEN 180
150 PRINT "YOU SHOULD LOOK FOR"
1 60 PRINT "A MAN OF"; 2*AG-1 4
170 STOP
180 PRINT'YOU MUST FIND"
1 90 PRINT" A GIRL AGED"; AG/2+7
200 STOP
Enter this program into the VIC and try it out.
For sensible values of age it will behave just like
the first version, but it will be much better at
detecting and refusing silly answers. It has the
important quality of robustness, or the ability to
stand up to abuse.
To end this unit, you will write a program of
your own. Before you start, here are some points
of advice:
1 . Get plenty of clean paper, a pencil and a
rubber. Switch off your computer.
2. Study the problem carefully, and work out
one or two simple examples yourself. Keep
the answers to check against the computer.
3. Begin by deciding what variables you need.
Jot down their names, types and purposes in
a "glossary". For instance, the variables for
the advisory program would have been
noted down as:
Name
Type
Purpose
AG
Number
Age of Client
SX$
String
Sex of Client, as
"MALE" or "FEMALE"
4. Draw a flow chart for the program. Be
Erepared to make lots of mistakes, and don't
e surprised if you redraw the chart half a
dozen times over. Keep on until you are satis-
fied. Programming is hard work, and this
part of the job — flow charting — is where
most of the effort comes.
5. Now translate your flow chart into BASIC.
This should be easy. If it isn't, it means that
you haven't done your flow charting
properly, so go back and do it again.
6. Now — atlast— switch on your VIC, and
enter the program. Apart from a few typing
mistakes, it should run without any bother.
Test it out on as many different examples as
you can, including one you worked out
earlier. Finally, preserve the program on
tape [if you want to keep it) and file away
your flow chart and variable glossary.
I have just described the way a good profes-
sional sets about programming. Lots of people
don't do it that way at all — they sit down in front
of their computers and compose their programs
straight on to the keyboard. This method some-
times works for very smal I problems, but usua I ly it
leads to long, uncomprehensible programs
which only work some of the time, ana which the
programmer finds impossible to alter or put right.
It also takes much longer to get dnythingworking
at all. However, this fact isn't at all obvious — it
seems quicker to ignore all the planning and get
on with the job. This, in truth, is why so many
people program so badly.
You have a choice; you can either do as
advised and quickly become a competent
programmer, or you can learn the hard way,
which will take you very much longer.
Now plan, flow chart, write and test a
program for the following problem:
In Ruritania the house-tax is levied as follows:
For each door: £57
For each window: £1 2
For each thatched roof: £38
For a tiled roof: £94
Assuming all houses must be either thatched
or tiled, write a program to ask for the details of
any house and display the house-tax payable.
For instance, the right answer for a thatched
cottage with one door and two windows would be
£(38+57+2*12)= £119.
Get your program to display the rates for the
following houses (assume all the doors and
Check your answer in Appendix B.
Experiment 1 7.2 Completed
EXPERIMENT
11-3
Load and run the program UNIT1 1 PROG.
When you have listed it, examine the code, and
draw up a flow chart and a glossary for it.
Experiment 7 7.3 Completed
u
u
u
□
u
u
u
□
u
u
u
u
□
□
□
u
□
LJ
u
□
u
u
□
□
□
□
u
□
u
u
u
u
u
u
You don't have to look deep into any
program to find a loop somewhere. Loops are so
common, and so important, that the BASIC
language gives you a short-hand method of
writing down the essential details.
You'll remember that there are four vital
parts to the control of any loop:
• The choice of control variable
• The starting value for the control variable
• The lastorfinal value forthe control variable
• The increment, or amount by which the
control variable grows every time round the
loop.
All these parts can be fitted into one special
command which uses the keyword FOR. This is
all that is needed to set up a loop except for a
NEXT command to mark the end of the loop body.
Compare the fol lowing two programs, which
give exactly the same result:
10FORJ=4TO20STEP2
20 PRINTJ,J*7
30 NEXT J
10 J=4
20 PRINT J,J*7
30J=J+2
40IFJ<22THEN20
(Using IF ... . THEN) (Using FOR ... . NEXT)
In both cases:
Control variable is J
First value is 4
Last value is 20
Increment is 2
The example shows how the FOR command
is built up
/ Always TO and A
20 STEP
First
value )/ Last
Control ^v/l value i >.
variable J V ^ >i
( Increment \
The NEXT command mentions the name of
the control variable, as a check to help you read
the program.
Every FOR command must have a corres-
ponding NEXT, and between them they enclose
the body of the loop.
In flow charts we show loops in a special
way, using blocks which can't easily be mistaken
for other kinds of action:
EXPERIMENT
121
To help fix the details of the FOR command in
your mind, look at the following short programs
and write down what you think they will makethe
VIC display. Then check your answers on the
machine itself:
(i) 10FORQ=1TO16STEP5
20 PRINT Q;
30 NEXT Q
40 STOP
Your prediction:
(ii) 10 FOR R=38 TO 50 STEP 3
20 PRINT R;50-R
30 NEXT R
40 STOP
Your prediction:
Now translate the following program into to
FOR-NEXT notation. Check your answer by
running both versions on the VIC and ensuring
that they give the same answers:
1 PRINT "NINE TIMES TABLE"
20S=1
30 PRINTS; 'TIMES 9 =";
40 PRINT 9*S
50 S=S+1
60 IF S<1 3 THEN 30
70 STOP
Your translation:
There are a few points about the FOR and
NEXT commands which you ought to remember:
(a) If the increment or step size is l,the "STEP 1"
at the end of the FOR command can be left
off. The VIC understands what is meant.
(b) The loop control can be made to count back-
wards by using a negative step size. The
program
10FORX=10TO5STEP-1
20 PRINT X;
30 NEXT X
will display:
in that order.
10 9 8 7 6 5
(c) The body of the loop is always obeyed at
least once, even if the final value is less than
the starting value. For example,
10 FOR R=5TO3
20 PRINT R
30 NEXT R
will display
(d) The values in the FOR command needn't be
numbers but can be expressions which
include other variables. For example, the
95
following program will display the number
of heart symbols requested by the user. Try it
out and study it carefully:
10 INPUT "HOW MANY HEARTS"; H
20FORK=1TOH
30 PRINT "^^H and I3A *";
40 NEXT K
50 STOP
(e) The control variable can't be a string. For
instance, the "command"
NOT BASIC
would give a SYNTAX ERROR, and you
aren't allowed to use this construction.
Using this knowledge, predict the outcome
of the following programs, and check your
results on the computer:
(i)
10FORA=1TO4
20 PRINT A*A;
30 NEXT A
40 STOP
(ii) 10FORB=3TO0STEP-1
20 PRINT B;
30 NEXT B
40 STOP
(iii)
10FORC = 5TO4
20 PRINT C;
30 NEXTC
40 STOP
(iv)
10X=5
20Y=9
30Z=2
40 FOR W=X TOY STEP Z
50 PRINT W;
60 NEXTW
70 STOP
So far we've been concentrating hard on the
details of FOR and NEXT commands, so we have
carefully chosen the bodies of the loops being
controlled to be as simple as possible. In practice
the body of a loop needn't be short and simple,
but can be as complex as you like — the thing to
remember is that it gets executed every time the
computer goes round the loop.
Suppose you've been asked to build a
square-basea pyramid, out of cannon-balls.
We'll number the layers 1 , 2, 3, — starting from
the top. Layer 1 , being the point, will need just one
cannon-ball. Layer 2, the second one, will need
four balls arranged like this:
Layer 3 will need nine balls, layer 4 — sixteen,
and so on.
Clearly the number of cannon balls you need
for the whole pyramid depends on how many
layers you plan to build. A three-layer pyramid
needs 1 +4+9 or 14 cannon balls; one with four
layers will require 1 +4+9+16or30.
If you plan a very large pyramid, these sums
will get rather long and boring, and you might
decide to write a computer program to do them
for you. This program will answer the question,
"How many cannon balls will I need for a
pyramid of 'so many' layers?".
In designing the program, a key factor is the
number of cannon balls in each layer. The
numbers 1 4 9 16 and so on look familiar,
and in fact you soon spot that the number of balls
in each layer is the square of the layer number.
For instance, layer 7 will need 7 * 7, or 49 cannon
balls.
Now for the details of the program. Let's
begin by thinking about the variables we'll need.
Our overall plan will be to consider the
layers one by one. We will get the computer to
work out how many balls are needed for that
layer, and add this number to a 'running total'. At
the beginning the running total must be set to
zero. At the end, when all the layers have been
taken into account, the running total will show the
number of cannon balls wanted for the whole
pyramid. This is the answer to the problem.
A suitable name for the running total is RT.
We need two other variables:
(i) The number of layers in the pyramid.
Remember that the programmer doesn't
know this number; it is up to the user to
supply any value he wants. A good name for
this variable is L.
(ii) As the program runs it will deal with layer 1 ,
then layer 2, then layer 3, and so on. We
need a variable to indicate which of the L
different layers the program is dealing with
at any moment. A suitable variable name is
V. Since V is going to take all the values
between 1 and L, the number of the bottom
layer, we can guess that it will be the control
variable in a FOR command, thus:
FORV=1TOL
NEXTV
The glossary for our program is thus:
Name
Purpose
RT
To keep running total of cannon balls
L
Number of layers in pyramid
V
Number of layer being dealt with at
any moment.
Next, we'll write down some of the actions
our program needs to take:
Add Vsquared (This adds in the number of
cannon balls for layer number V)
toRT
Print RT
SetRT=0
Input L
(Displays result)
(Starts RT off from zero)
(Asks user how many layers
there are in his pyramid)
FOR V= 1 TO L (Loop control for taking every
NEXTV
STOP
layer into account)
These are all the fragments of program we
need, but they have still to be put together in the
right order. We have already decided that there
must be a loop, and it will greatly help us if we
can say, for each command, whether it should be
executed
before the loop starts
or inside the loop (as part of the loop body)
or after the loop has ended.
We can use various clues. The program has
to know how many times to go round the loop
before the loop itself can start, so input L must
come before the loop. So must the command
which sets RT to zero.
The total number of cannon balls for the
whole pyramid includes at least some for each
layer. The command to add a layer's worth to RT
has to be repeated many times, and so it goes
inside the loop.
Finally, the computer can't give you the right
answer until it's taken all the layers into account,
so the PRINT command can only come after the
loop has ended.
Now we've got far enough to draw a flow
chart. It is
t
INPUT L
RT
=0
96
E
FORV
1
L
1
ADDV*V
TORT
And the corresponding program is
1 INPUT "NUMBER OF LAYERS"; L
20 RT=0
30FORV=1TOL
40 RT=RT+V*V
50 NEXTV
60 PRINT RT;"CANNON BALLS NEEDED"
70 STOP
Enter this program and try it out.
Now here is a problem for you. In the game
of cricket, a player can have a number of separate
EXPERIMENT
12-2
'innings' during the season. Each time he scores
some 'runs': many if he is a good player or lucky,
or only a few (or even none) if he isn't so skilful. If
you want to know how well someone has played
over the whole season, you work out the average
number of runs per innings. You get it by adding
up all the runs he gains over the season and
dividing by the number of innings. For instance, if
he plays three times and scores 20, 30 and 70, his
average is (20+30+70) +3 or 40 runs per innings.
Consider a program which does this calcula-
tion for you. It has to ask you for the number of
innings, and then the score for each one, so that it
can add them up together. The overall display
would be like this:
RUN
NUMBER OF INNINGS? (3
Numbers
typed by
user
SCORE? (20
SCORE? (30)
SCORE? (70
AVERAGE = 40
Your job is to write the program for this
problem. To make it easier, we'll give you a
glossary and all the commands, but in jumbled
order and with their labels stripped off. Begin by
drawing a 'skeleton' with the loop commands,
and then slot in the other commands in the right
places. Finally, run the program on the VIC and
make sure that it works. If you get really stuck,
look up the correct answer in Appendix B, but
remember: this is an admission of failure!
The glossary and jumbled commands are:
Name
Purpose
J
Number of innings during season
Q
Control variable for loop
RS
Used to add up the total runs scored
S
Score for each separate innings
NEXTQ
INPUT'NUMBER OF INNINGS"; J
INPUT"SCORE"; S
PRINT"AVERAGE= ";RS/J
STOP
RS=0
FORQ=lTOJ
RS=RS+S
Experiment 12. 1 Completed
We end this section with a problem which
you must solve without any help. If you go to the
Post Office, you are quite likely to get stuck in a
queue just behind someone buying a huge
amount of stamps. You hear her saying:
"Eighty-three at lip
and One hundred and seventeen at 14p
and Thirty-five at 75p"
and so on. When all the stamps have been
counted out, the clerk spends ages working out
how much it all costs.
Write a program to help the clerk. The
display should be something like this:
RUN
NUMBER OF BATCHES?
BATCH 1
NUMBER OF STAMPS?
VALUE (EACH)?
BATCH 2
NUMBER OF STAMPS? (?)
VALUE (EACH)?
BATCH 3
NUMBER OF STAMPS?
VALUE (EACH)?
BATCH 4
NUMBER OF STAMPS?
VALUE (EACH)?
TOTAL DUE=2079 PENCE
The program should be 10 commands long
[including STOP). Four of these commands will
form the body of a loop, obeyed once for each
batch. However, don't try to write the program
yourself until you have a proper design, with
glossary and flow chart. Take plenty of time.
If, after spending a good deal of effort, you
still can't get this problem right, go back a few
units to a place where you feel confident, and
work through the course material again.
Finally compare your answer with that given
in Appendix 8.
Experiment 12.2 Completed
The self test quiz for Unit 1 2 is called
'UNIT12QUIZ".
u
u
u
□
u
u
u
□
u
u
u
u
□
□
□
u
□
LJ
u
□
u
u
□
□
□
□
u
□
u
u
u
u
u
u
UNIT:13
EXPERIMENT 131
PAGE 101
EXPERIMENT 13-2
105
EXPERIMENT
131
101
This unit is about a topic which is both easy
and fun: using the VIC to make sounds and
musical notes.
Load the program entitled SOUND DEMO,
turn up the volume control on your TV set, and
play through the selection of sound effects the
program provides.
As you wi 1 1 hear the sounds that can be made
are wide ranging and give an indication of what
the VIC can ao. Undoubtedly you will want to
design your own sounds, and this is what the rest
of this unit is all about.
The sound production unit on the VIC is con-
trolled by POKE commands. The unit has five
special addresses, arranged like this:
36874
BASS
36875
TENOR
36876
TREBLE
36877
NOISE
VOLUME
-To TV set
36878
On the left are four electronic 'voices'. Each
of them except 'noise' will sing a clear musical
note if a number is POKE'd into the right address.
For instance, the treble voice will start singing
middle C when you give the command
POKE 36876, 131
The pitch of the note depends on the number
vou poke. 1 28 gives the lowest note, and 254 the
highest. The notes are not equally spaced, and
the stave at the foot of the page shows how the
pitches correspond to the notes on the piano.
To stop the treble voice, you command it
POKE 36876,0
(although POKE'ing any number between and
1 27 wiltnave the same effect).
On the right of the diagram there is a mixer
and volume control. It combines the sounds
made by the four voices and sends them to the
loudspeaker in the TV set. You can adjust the
loudness of the sound by POKE'ing numbers
into the volume control address:
POKE 36878, 15 is fortissimo, or full blast
POKE 36878, 1 is pianissimo or very quiet
POKE 36878,
gives silence (even if the
voices themselves are still
singing).
Numbers between 1 and 15 give increasing
degrees of loudness.
Note that the VIC's volume control is quite
separate from the knob or slider on your TV set.
The TV control should be set when you first switch
on, and then left alone, leaving the VIC to change
the loudness of the sound according to the
program it is running.
i
OQO
4
oflo
o
*
f
OBO'
CO
CO
oo
— ' VI
CN
VI
VI
to
VI OO 00 oo -o
VI — ' en vO CO
— I-O
-o o
CN O
SJ IO (O NO fO IO w
o O O — ■ — ' — — •
CO nO — • ^ O CO
NJ NO SO
to to SO
O IO J>.
Treble Voice
Now you know how to make the VIC
produce any note, with any degree of loudness.
For instance, this program will make it play a G at
about half-volume:
10 POKE 36876, 172
20 POKE 36878, 8
If you run this program you will see (or rather
hear) a serious difficulty: the note continues to
sound even when the program has ended and the
READY message has appeared. To reduce the
volume to zero type the command
POKE 36878,
A diffe rent w ay of stop ping the so und is to
hold down UlSli and strike ■■■■■ .
This experiment brings us to another vital
point. One of the most important features of a
sound is how long it lasts. A program running in
the VIC must time the sound it makes, using a flow
chart like this one:
i
Start the
sound
Stop the
sound
A simple way to make the computer keep
time is to make it obey an 'idle loop': that is, a
loop without a body. While going round this loop,
the VIC spends all its time counting and testing.
Roughly speaking, the machine can get round an
idle loop 1 000 times every second, so that a one-
second wait could be written as
FOR M = 1 TO 1000 ^
NEXTM ^ — (note: no loop body)
The control variable (in this case M) has
been picked at random. In practice you can use
any name, as long as it is different from the other
names in your program.
Notes lasting any length of time can easily be
programmed by choosing the rightfinal value for
the idle loop: 3000 for 3 seconds, 500 for half a
second ana so on.
Let's write a program which sounds a 'pip'
like the ones on the radio. The right pitch for the
treble voice is about 235, and the pip itself lasts
for Vio of a second. Turning our flow chart into
code we get
10 POKE 36878, 15
20 POKE 36876, 235
30FORM=1TO100
40 NEXTM
50 POKE 36876,0
Type NEW and enter this program into the
VIC. When you run it, the program will give a
single 'pip' and then stop.
Next, you can modify the program and get it
to give out a whole chain of pips one after the
other. Basically you could make the program into a
loop by adding a GOTO to jump from the end
back to the beginning, but this by itself wouldn't
be enough. The pips would come so close to each
other that they would sound almost like a
continuous note. To get the right pattern of
sounds you must make the program wait in
silence before going back. Each pip lasts one
tenth of a second; so to get a pip every second,
the right time to wait is nine tenths. Add the
following commands to your program and try it
out:
60 FOR Q=l TO 900
70 NEXT Q
80 GOTO 20
When you've got this program running, try
some experiments: change the pitch of the note,
and the timing of both the pip and the silence, and
see the effects for yourself. Finally, change the
program back to its original form.
Now lef s think about a very similar problem :
how to get a program to give out a given number
of pips (say 6) ana then stop. If you take away the
GOTO at line 80, you already have a program
which sounds one pip, followed by a silence of
the right length. To get 6 pips, all you need do is to
make this program into the body of a loop which
is obeyed six times. You get
FOR J
1
6
1
The conversion is trivial:
5 FOR J=l TO 6 (at the beginning)
and 80 NEXT J (at the end)
90 STOP
Try it!
Now list your program. You will see that
inside the body of the main loop (with control
variable J) there are two inner loops (with control
variables M and Q). This means that the whole of
each inner loop, 1 00 times round for M, and 900
times round for Q, is obeyed for every value of J
in the outer loop. During the execution of the
entire program (6 pips) the VIC goes round the M
loop 6 x 1 00 or 600 times, and round the Q loop
6 x 900 or 5400 times.
This is our first example of a loop inside
another loop. These 'nested loops' are extremely
common, and they are easy to use if you
remember to choose different control variables
for each one.
You get interesting effects if you change
either the pitch of a note or its volume while it is
being sounded.
Try the following program:
NEW
and
10 POKE 36878, 15
20 FOR C= 180 TO 220
30 POKE 36876, C
40 NEXT C
50 POKE 36878,0
As this program goes round its loop, 41 times
in all, a higher number is POKE'd into the treble
voice each time. The effect is to give a sound
rising steadily in pitch. This sound could be the
basis of a police siren, or a space-ship taking off.
The trouble is that the sound is over much too
quickly; you might like to slow it down and make
it last a little longer.
One good way of stretching out the sound is
to put a short idle loop into the main one. Try
inserting
33 FOR M=l TO 20
36 NEXT M
You now have a basic program for a 'rising
tone'. You can 'tune' it in all sorts of ways by
changing the starting and ending value for C, or
the final value for M. For example, if you alter line
20 to read
20 FOR C = 130 TO 170
you'll get a howl of much lower pitch. If you put
33 FORM = 1 TO 200
your tone will last about 1 times as long. Finally,
if you use a negative step size, like this:
20 FOR C = 200 T0 1 50 STEP -1
the machine will sound a falling note instead of a
rising one.
The effect of changing the volume of a note
depends very much on now quickly it happens. A
very slow change sounds like something
approaching or going away, but a rapid reduc-
tion from full volume can make a note sound like
a plucked instrument — a guitar, harp or harpsi-
chord (but not a violin or 'cello).
Here is a program to let you try out the effect
for yourself. Its flow chart is:
Start treble
voice on note
'C
1
1
FOR J
15
-1
and the program itself is:
10 POKE 36876, 193
20FORJ = 15TO0STEP-1
30 POKE 36878, J
40 FORM = 1 TO 100
50NEXTM
60 NEXT J
70 GOTO 10
Now try your own hand at programming
dramatic sounds. See how well you can imitate
(a) A fire engine
(b) A police siren
When you have done as well as you can,
look up Appendix B and compare your answers
to the programs you find there.
Experiment 13.1 Completed
104
EXPERIMENT
So far we have only used the treble voice
(address 36876). This section is about the other
three voices.
The tenor voice (36875) sounds the same
notes as the treble, but one octave lower. (An
octave, as you will know, is a span of 8 white
notes on the piano.) The bass voice (36874) is an
octave lower again, and can be used to make low
rowling sounds which suggest robots, haunted
ouses, and so on. Try this program and see if
you can work out why the pitch goes up and the
pips come faster and faster.
10FORJ = 130TO240STEP3
20 POKE 36874, J
30 POKE 36878, 15
40 FORM = 1 TO 100
50 NEXT M
60 POKE 36878,0
70 FOR Q = 1 TO 350— J
80 NEXT Q
90 NEXT J
100 STOP
You can play more than one voice at a time,
but they blend best if they are each made to sing
notes an octave apart.
The fourth voice is used to produce electronic
noise, to imitate rockets or explosions. The 'pitch'
of the noise depends on the number you poke into
address 36877. It is low like a distant charge of
dynamite if the number is small (say between 1 30
and 1 40) . If you poke a high number (such as 250)
the noise sounds much more like a jet engine.
Noises often sound more effective if they
start loud and fade away. This can be arranged
by starting the volume at 1 5 and bringing it down
gradually.
Type NEW, Wd and Hjiifl / and try
this program:
1 FOR K = 1 30 TO 250 STEP 5
20 POKE 36877, K
30 FORJ = 15TO0STEP-1
40 POKE 36878, J
50 FORM = 1 TO 100
60 NEXT M
70 NEXT J
80 NEXT K
90 STOP
It should give you a good idea of what the
various pitches of noise sound like. This program
has three nested loops, but that shouldn't worry
you:
The outer loop (controlled by K) makes the
machine work through the pitches 130, 135, 140
250.
The middle loop (controlled by J) makes the
program reduce the volume of each sound by
working down from 15 to 0.
The inner loop (controlled by M) simply gets
the machine to wait Vio second between each
change of volume.
When you have run this program several
times, insert a new command:
55 PRINT M;
The machine now displays every value of M,
every time round the inner loop. This slows every-
thing down quite a lot, and gives you an idea of
how much is really going on!
To end this unit, experiment with the VIC
sounds. Then choose one of the following and
imitate it as well as you can:
(a) Jet flying overhead
(b) Ship's klaxon
(c) Horn on railway engine
(d) Morse code letter V (dot-dot-dot dash)
Write down your program for future use.
Experiment 13.2 Completed
Ifyou can use a musical keyboard, the
PIANO program will let you playa novel musical
instrument. Use the top two rows of keys on the
keyboard to play the notes.
UNIT:14
EXPERIMENT 14-1
PAGE no
EXPERIMENT 14-2
113
107
In this unit we'll look at an extremely common
type of computer application: one where the
machine is made to input and digest a large
number of separate items of information, and to
display a summary of its results. For instance, if
you wanted to keep track of your bank account,
you could feed in the details of every cheque you
write, and every credit you pay in to the bank, and
the machine would tell you your balance at the
end of the week. To give another example, a
school teacher couldgive the computer all the
exam marks gained by the pupils in the class, and
the computer would display the overall average
mark.
All programs of this type conform to the
same basic pattern, which has a flow chart
something like this:
A very simple example is this program which
inputs 1 numbers and finds their average value:
Initialise
10S=(
20 P=l
30 input;
40S=S+X
50 P=P+1
60IFP<11THEN 30;
70 PRINT" AVERAGE="; S/10 \ Dis P la y
) summary
80 STOP
Read and digest an item
Any more items?
Display
summary
Glossary
S: Used to add up values of items
P: Used to count the items
X: Used to input individual items
If you don't understand how this program
works, trace it with the input values 3, 6, 2, 7, 0, 9,
8,3,12,10.
In this example, we've used an IF-THEN for
the loop control to make the construction of the
program more clear. In practice we would write
the program with a FOR . . NEXT, like this:
10S =
20FORP= 1 T0 10
30 INPUT X
40S = S+X
50 NEXTP
60 PRINT "AVERAGE IS"; S/l
70 STOP
Let's think about the part of the program
which says "any more items". In the first example
the question was answered by keeping a simple
count, and using the condition P < 1 1 , which was
true until the tenth item was input and added to
the running total. This method depends on the
programmer knowing in advance how many
items there are going to be. The method is almost
useless in practice because it is so inflexible: you
would need different programs to find the
average of 11 , or 20 or any other number of
numbers.
You can write a much better program if you
assume that the user can tell the computer how
many items to expect. The following program will
work for any number of items:
10S =
20 INPUT "HOW MANY NUMBERS"; N
30FORP=1TON,
40 INPUT X
50 S = S + X
60 NEXT P
70 PRINT "AVERAGE IS"; S/N
80 STOP
Glossary
S: Used to add up value of items
P: Used to count the items
X: Used to input individual items
N: Used to hold the number of items
So far we have been on familiar ground; but
what about the case where the user has to feed in
a large number of items (like a thousand or
more)? It is unfair to make him count the items in
advance, and unrealistic to suppose that he'll get
the number right.
A different way of controlling a loop is not to
use a predetermined count at all, but simply to tell
the computer when the stream of items has
ended. We could, for example, get the user to
answer the question "any more items" each time
round the loop. This would lead to a program like
10S=0
20 N=0
30 INPUT "NEXT NUMBER"; X
40S=S+X
50 N=N+1
60 INPUT "ANY MORE NUMBERS"; M$
70 IF M$ = "YES" THEN 30
80 PRINT "AVERAGE IS"; S/N
90 STOP
Glossary
S: Used to add up values of items
N: Used to count items
X: Used to input individual items
M$: Used to hold answer to question
"Any more items"?
If you ran this program, the display might be:
NEXT NUMBER? 4
ANY MORE NUMBERS? YES
NEXT NUMBER? 7
ANY MORE NUMBERS? YES
NEXT NUMBER? 10
ANY MORE NUMBERS? [NO
AVERAGE IS 7
BREAK IN 90
READY
The drawbacks of this scheme are clear. The
unfortunate user has to keep typing YES after
every number except the last. This takes double
the time, and doubles the risk of mistakes. A
better method is to mark the end of the stream of
items with a special value called a terminator. A
good choice for a terminator is a value which
couldn't possibly occur as one of the items. For
instance, if you plan to use the program to
average football scores, you could use the
number 1 000000, because you may be sure that
no team can ever score a million goals in one
match.
The display produced by a program written
on these lines could be:
USE 1000000 TO
END INPUT
NEXT NUMBER? [Tf-
User
types
NEXT NUMBER? [7}
NEXT NUMBER? [jj}
NEXT NUMBER? |T)-
NEXT NUMBER? |T|-
NEXT NUMBER?
AVERAGE IS 3
BREAK . . .
To use this system we have to re-arrange the
overall flow chart; in particular, the question
"any more data" must come before the block
which digests each data item — otherwise the
terminating value would be treated as an
ordinary item and would upset the summary.
The corresponding program for finding an
average is quite straightforward:
1 PRINT "USE 1 000000 TO"
20 PRINT "END INPUT"
30 S=0
40N=0
50 INPUT "NEXT NUMBER"; X
60 IFX=1000000THEN100
70S=S+X
80N=N+1
90 GOTO 50
100 PRINT "AVERAGE ="; S/N
110 STOP
Glossary
S: Used to add up values of items
N: used to count items
X: Used to input individual items
To summarise, we have looked at four dif-
ferent ways of indicating how many items of
information are to be input by a program. They
are:
1 . Number of items is specified by the
programmer. Used only by beginners and
useless in practice.
2. Number of items is specif ied in advance by
the user. A good method if there are 20 items
or less.
3. User indicates after each item if there are any
more to follow. Intolerably tedious.
4. Stream of items ends with special value. A
good method, generally better than the
others.
EXPERIMENT
141
Hint: Your display section will be a little more
complex than usual. If B is a variable which
gives the current balance, then it will be
negative (or less than zero) if you are over-
drawn at the bank. The right condition to
check this possibility is B < 0. Your solution
should include a flow chart and a glossary.
Check it against the answer in Appendix B.
Experiment 74. 7 Completed
Write a simple banking program which
inputs your old balance, and details of all the
cheques you have written, and then displays your
new balance or overdraft. Use the number zero
as a terminator, because you will never write a
cheque for £0.00. Don't worry about credits.
Design your program so that it could produce
either of the two displays which follow:
(a) OLD BALANCE?
TYPE DETAILS OF
CHEQUES, USE TO END
AMOUNT?
1.73
AMOUNT?
2.00
AMOUNT?
YOUR BALANCE IS £1.51
Typed by
user
(b) OLD BALANCE?
TYPE DETAILS OF
CHEQUES. USE TO END
AMOUNT?
AMOUNT?
AMOUNT?
AMOUNT?
YOUR OVERDRAFT IS £3.98
In some problems the various items in the
stream have to be treated in different ways. The
corresponding programs generally have 'IF'
commands inside their main loops. For example,
let's suppose that after a run of very bad luck in
gambling you became suspicious that a coin was
iased, so that it came up 'heads' much more
often than 'tails'. You could follow up your hunch
by tossing the coin a large number of times, and
counting the number of heads and tails which
came up. You mightwantthe VICto helpyou keep
the score, so you would write a program which
produced a display like this one:
TYPE H FOR HEADS
T FOR TAILS
E FOR END
NEXT THROW?
NEXT THROW?
NEXT THROW?
H
Typed by
user
. . . . unu :
. and so on for 547 lines
NEXT THROW?
OUT OF 547 THROWS
THERE WERE 490 HEADS
AND 57 TAILS
READY.
And you could draw your own conclusions
about the bias of the coin.
Let's design and write this program, from
glossary and flow chart down to BASIC
commands.
The sample output shows that we use a
special value, E, to terminate the stream of data
items. The outline flow chart will be the same as
the one on page 1 09, and all one need do is
expand the clouds.
The program obviously needs three
variables:
H: To count number of heads
T: To count number of tails
1$: To input an item
(As usual, the names H and T are freely chosen.)
Some people might be tempted to include a
fourth variable to count the total number of
tosses, but there is hardly any point; the total is
always given by the expression H + T (the
number of heads plus the number of tails).
Next we can work out the initialisation section
of the program. There are two things to do:
• Set variables H and T to zero
• Display the heading message.
Next we turn to the cloud inside the main
loop, which digests each new item. By this stage,
the 'E' will have been filtered out, and every item
ought to be an H or a T. The basic job the cloud
has to do is to add 1 either to the heads total, or to
the tails total. One possible approach would use
the argument "Is it an H? If not, it must be a T".
This would result in a flow chart like
Is item
\an "H"?^
Yes
Add 1 to
H
TNo
Add 1 to
T
T *
In practice, this method would never be used
by a good professional programmer, because it
doesn't allow for the user'styping mistakes. If the
userhitsa J instead of an H (they are nextto each
other on the keyboard) the program would count
it as a T, which is most unlikely to have been what
the user wanted.
It is much better to allow for the possibility of
errors, like this:
Add I to
H
"No
Add I to
T
No
Display an
error message.
A program which allows the user to make
mistakes without disastrous consequences is
called robust.
Finally, we can expand the "summary" cloud
to.give the three-line report at the end of the
display. The expanded flow chart looks like this:
■ ' 1
Set: H=0
T=0
Yes
Display:
Outof (H+T) Throws
there were H Heads
and T Tails
Display:
Type H for Heads
T for Tails
E for End
Input 1$
No
Yes
—
Yes
H=H+1
T=T+1
Display:
Wrong item
The corresponding program is written out
below. Notice that the code forthe main loop isa
bit tangled. This is unavoidable since we have to
force a two-dimensional flow chart into a single
stream of instructions.
10H=0
20T=0
30 PRINT "TYPE H FOR HEADS"
40 PRINT "T FOR TAILS"
50 PRINT "E FOR END"
60 INPUT "NEXT THROW"; 1$
70IFI$="E"THEN160
80IFI$="H"THEN120
90IFI$='T"THEN140
1 00 PRINT "WRONG ITEM"
110 GOTO 60
120H=H+1
130 GOTO 60
140T=T+1
150 GOTO 60
160 PRINT "OUT OF"; H+T; 'THROWS"
1 70 PRINT 'THERE WERE"; H; "HEADS"
1 80 PRINT "AND"; T; 'TAILS"
190 STOP
EXPERIMENT
14-2
(a)
If a program has a great deal of input, the
user may stop looking at the screen as he
types. It is a good idea to make the program
react with sounds as well as displayed
messages. You could, for instance, use a
cheerful 'pip' for an item which is acceptable,
and a rude noise for one which isn't.
Look at the heads and tails program. Every
time the user types an H the machine obeys
the commands at lines 1 20 and 1 30. We
could insert a suitable noise by adding the
commands:
(b)
121 POKE 36878, 15
122 POKE 36876, 230
123FORM = lTO
124 NEXT M
125 POKE 36876,0
126 POKE 36878,0
Load the HEADS program from the cassette
tape (this saves you keying it in for yourself)
and edit it so that it answers each input (right
or wrong) with a suitable sound.
At one time, clocks were liable to a curious
form of tax, which was calculated as follows:
If the price of the clock was less than £1 2, the
tax was one-third of the cost.
If the price was between £1 2 and £1 6, the tax
was £4.
If the price was over £1 6, the tax was one-
auarter of the cost of the clock!
Write a program which inputs a list of clock
prices/ended by 0, and displays the total to
be charged for each clock (including cost
and tax).
Note that this program will have one or more
PRINT commands inside the loop, and
doesn't need a summary block. You will find
a good flow chart indispensable.
u
u
(c) Write a program which inputs a stream of
numbers ended by 0, and displays the
largest.
Hint: use a variable to record the largest
number so far, and update it every time
round the loop.
Experiment 14.2 Completed
Now check your answers in Appendix B.
u
u
u
□
u
u
u
□
u
u
u
u
□
□
□
u
□
LJ
u
□
u
u
□
□
□
□
u
□
u
u
u
u
u
u
UNIT:15
EXPERIMENT 15-1
PAGE 117
- EXPERIMENT 15-2
122
_ EXPERIMENT 15 3
122
EXPERIMENT 15-4
125
117
This unit is about three important features of
Commodore BASIC which are useful in games,
quizzes and other programs where the machine
and its user work closely together.
We'll begin by having a look at "REACTION",
one of the programs you'll find on the cassette
tape. A person's "reaction time" is a measure of
how quickly they can respond to an unexpected
event. A safe driver should have a fast reaction
time, so that he or she can put the brakes on
quickly when a child runs out into the road in front
of the car. A good reaction time is also useful in
most sports and many professions.
Most people, if they are paying attention,
have reaction times between 0.2 and 0.3 of a
second (twenty to thirty hundredths of a second).
A time of less than 0.2 suggests someone who is
quick on the uptake, whilst a reaction time of
more than 0.3 is usually due to a few drinks too
many!
EXPERIMENT
15-1
Load the REACTION program, and use it
to measure your own reaction time. Run the
program several times, and ignore the first two or
three results, since they will not be typical. Keep
trying the program until you are satisfied that you
understand it thoroughly, and could confidently
use it to measure the reaction time of a friend who
had no knowledge of computing.
You may notice three aspects of the program
which are not immediately obvious:
First, when the instructions say "any key",
they really mean it. You will find that function keys
work just as well
like ^mmni^j and I
as letters or numbers.
Second, the time you must wait before
hearing the tone is always different: it varies
between 1 and 6 seconds in a way you cannot
predict in advance.
Third, if you press a key before the tone
starts, you get a message, 'TOO SOON".
Now we'll examine the program in detail,
and explain how it works. Let's start by examining
the flow Chart and BASIC program, which are
shown below:
■o
3 .
o
Clear screen and
give instructions
Wait for user to
Cloud 1
hit a key
Cloud 2
Wait a random time , _. lo
between land 6 / Cloud3
seconds
Start tone. Record J q ouc | 4
1 current time " J '
vWaitfor user to
hit a key
Cloud 5
Record current time ) Cloud 6
Stop tone
fSTOPj
10 REM RE ACTION T IME PROGRAM
20 PRINT "^BB and B "
30 PRINT "TO MEASURE YOUR"
40 PRINT "REACTION TIME:"
50 PRINT "HIT ANY KEY"
60 PRINT 'THEN WAIT FOR THE"
70 PRINT 'TONE. WHEN YOU"
80 PRINT "HEAR IT, HIT ANY"
90 PRINT "KEY AS FAST AS"
'1 00 PRINT "YOU CAN. GOOD LUCK!'
CN
"D
3
_o
u
j
_Q
a>
a>
in
-a
c
CO
"O
3
_o
u
-a
3
_o
u
f 110 REM WAIT FOR ANY KEY
120 GET A$
130 IFA$ = " "THEN 120
^ 1 40 REM WAIT A RANDOM TIME
143 PRINT
145 PRINT "WAIT FOR IT!"
148 PRINT
1 50 Q=TI+INT(60+301 *RND(0))
160 GET A$
170 IF A$<>"" THEN 340
V 180 IF TI<Q THEN 160
/ 1 90 REM START TONE AND NOTE TIME
200 POKE 36876, 225
210 POKE 36878, 15
^ 220X=TI
230 REM WAIT FOR ANY KEY
240GETA$
I 250 IF A$="" THEN 240
/ 260 REM GET RESULT AND STOP TONE
270 R=TI
280 POKE 36876,0
V 290 POKE 36878,0
f 300 REM DISPLAY RESULT
31 PRINT "YOUR REACTION TIME IS"
I 320 PRINT (R—X)/60 ; "SECONDS"
330 STOP
*o^ ( 340 PRINT 'TOO SOON"
<£o I 350 STOP
m
3
_g
"D
3
JO
u
rv.
3
o
119
The program has been marked so that the
commands which correspond to each cloud in the
flow chart are clearly visible.
The first cloud (lines 1 to 1 00) consists
entirely of PRINT commands and is quite straight-
forward.
The second cloud, lines 1 10 to 130, makes
the program wait until the user types a key. The
cloud uses a command with a new keyword:
GETA$
This command is in some ways like INPUT; it
transfers information from the keyboard to the
computer. However, there are some very
important differences:
1.
2.
The keyword GET must be followed by
exactly one string variable name. The names
of number variables are not allowed. For
example
Not BASIC
GET X$ . but
GET PR$
(allowed) V (forbidden)
The GET command doesn't wait for the user
to do anything; it simply examines the key-
board atthat instant ana indicates which key
has been typed since the last GET or INPUT
command was obeyed. If a key has been
struck, it is made into a one-character string
and put into the variable mentioned in the
GET command. If no key has been newly
struck, the variable is set to the null string.
This is a string with no characters, and is
normally written as" ".
To illustrate this rule, imagine that we start off
the computer on the following looped
program, and watch what happens inside
the machine:
10GETX$
20 GOTO 10
The computer will go round this loop about
50 times a second. As long as the user
doesn't touch the keyboard, X$ will be set to
the null string : " ".
Now suppose the user presses down a key —
say the one marked U. As soon as the GET
command is obeyed (i.e. within a fiftieth of a
second) X$ will be set to the string "U".
However, this only happens once for each
key depression; the next time round the loop
X$ will again be set to " ", and this will
continue until the U key is let go and another
key (or possibly the same key) is pressed.
The only exceptions to this rule are the so-
called repeating keys like space.
3. The GET command doesn't treat certai
in
INST 1
DEL 1
RETURN
control characters like
or cursor controls as special cases, but deals
with them all in the same way, except for
STOP, which interrupts the program.
4. Any character which is detected by the GET
command is nof displayed on the screen.
With these points in mind, you can now begin
to make some sense of line 1 20 and 1 30 in the
REACTION program. Command 120 examines
the keyboard and delivers a string in A$ which is
null unless a key has been pressed. Command
1 30 tests A$, and makes the computer loop back
to 1 20 until the user types any key, at which the
program is allowed to drop through to line 1 40.
The point of this cloud is to hold the program
up until the user shows he is ready to have his
reaction time tested. Why do we use a loop with a
GET, instead of a single command like
INPUT "READY"; A$ ?
There are two reasons. First, INPUT always
expects a ^mmm^p after the user's message.
This implies a minimum of two characters to be
typed.
Second, GET treats nearly all the characters
in the same way, so there is much less chance of
the program being spoiled if the user hits a
function key instead of a letter or number.
Cloud number 3 makes the machine wait a
random (that is, an unpredictable) time between
the user's 'ready' signal and the tone. The waiting
time must be variable, because if it were always
the same, the user would soon learn how long to
wait before the tone was due, and this would no
longer be an 'unexpected' event.
The cloud uses two facilities which you
haven't met before: the random function and the
internal timer.
! I
The random function is a way of making the
machine produce an unpredictable* number.
Every time the machine works out the expression
RND (0) it gets a different value somewhere
between and 1.
In most practical cases, we don't need a
random fraction between and 1 , but a random
whole numberwithin limits which depends on the
problem to be solved. For instance, if you make
the machine imitate someone throwing a 6-sided
die**, you expect a number between 1 and 6; or if
you model a (European) roulette wheel, you need
a number which is between and 36.
To get a whole number in any specified
range, we use a slightly different expression:
INT(x + y ★ RND(0))
where x is the lowest number we need
y is the number of different possibilities
So, to get a number between 1 and 6, we
would put
*7he number isn't really unpredictable because
everything which happens in a computer
depends on what happened previously.
However, each new 'random' number is derived
from the previous one by a complicated process
of squaring it and shuffling the digits of the result,
and unless you know exactly how it is done you
cannot tell what number is coming next.
**That is: one of a pair of dice.
An expression of this sort can be included in
a loop, so that it is worked out many times. Type
the following program, which imitates 1 20 throws
of a die:
NEW
10FORJ = 1TO120
20 S = INT(1 +6* RND(0))
30 PRINTS;
40 NEXT J
50 STOP
Run this program, and count the number of
* 1 's, 2's . . . 6's which appear on the screen. Enter
your results in the first row of the table below:
1
2
3
4
5
6
No. of throws (1)
No. of throws (2)
Is the program a good imitation of a fair (or
unbiased) die?
Now run the program again, and fill in the
second row. Examine the results and note that
they are different from the first run, just as you
would expect with a real die.
The other important feature in cloud 3 is the
internal timer, Tl. We have already met the clock
Tl$, which keeps time in hours, minutes and
seconds; but the special variable Tl (which is not
a string but a number) is intended to measure
much shorter periods of time. Tl is set to zero
when the VIC is started up, and from then on, no
matter what else happens, it has 1 added to it
every 60th of a second. This interval, a sixtieth of
a second, is called one "jiffy". You can get the
current value of the internal timer at any time in
jiffies by using the name Tl in an expression; but
you can't alter the value in the way you can setTI$.
Give the command
PRINT Tl
The machine will respond by displaying a
fairly large number (60*60 or 3600 jiffies for
every minute you've had the machine switched
on). Now try the command again, and observe
that the value has gone up by a few hundred Or
so. Finally, try to reset the value of Tl and see what
happens!
Tl can be used to measure periods of time in
two different, but related ways. In neither of them
are we interested in the number of jiffies since the
VIC was switched on; instead, we use the fact that
the duration of any length of time is given by the
difference between Tl at the end of it, and the
value it had at the beginning. For instance, at the
end of a period of 5 seconds, Tl will be 5 * 60 or
300 more than it was at the beginning. This is true
whether the machine has been switched on for 5
seconds or 5 years.
In the first way of using the internal timer, we
make the machine measure a period of time
which is known in advance, and tell us when
that time has elapsed. The method is simple. At
the beginning of the period the program looks at
Tl and predicts what it should be at the end of the
period; then it waits in a loop until Tl reaches (or
passes) that value. This is very like what you do in
the kitchen, when you say, "These potatoes must
boil for 25 minutes. Now it's ten past four, so I'll
take them off at 4.35".
To illustrate the point, here is a general
purpose timer program, which you could use in
the kitchen, the laboratory, etc.
1 INPUT "HOW MANY MINUTES"; M
20 R=TI+M*3600
30IFTI<RTHEN30
40 PRINT 'TIME UP!"
50 STOP
If you try this program out, use a small
number of minutes, otherwise you'll spend a lot of
time waiting. As you study the program,
remember that Tl is moving upall the time, so that
eventually, after M*3600 jiffies, the condition
TI<R will be false.
In the second variant, we want the computer
to tell us how iong it takes from a given moment
until some event occurs. We get the machine to
record the value of Tl at the beginning of the
timing period. When the event comes, the differ-
ence between the value of Tl now and the value
recorded is a measure of the length of time, in
jiffies. It is rather like the mountaineer who says,
"I remember that I started climbing this hill at 5
o'clock. I have just got to the top at eleven o'clock,
so it must have taken me six hours."
A program which measured time in this way
would have commands something like this:
R=TI (Stores value of Tl at beginning of
period)
and later
E=TI Gets value of Tl at end of period
D=E-R Gets difference of times (in jiffies)
S=D/60 Gets time difference (in seconds)
PRINT'THATTOOK"; S; "SECONDS"
Now we can piece together the commands in
cloud number 3.
We want a waiting period of between 1 and
5 seconds. This is between 60 and 300 jiffies, to be
decided by the machine in an unpredictable way.
The appropriate expression is
INT(60+301 ★RND(0))
The waiting period is decided just before the
period starts, so it is known in advance (although
not to the user). We use the first method of timing,
which involves predicting the value of Tl at the
end of the period. Command 1 50 makes this
prediction and records the value in Q.
If this were all that were needed, the entire
cloud could read:
150 Q = TI+INT(60+301 *RND(0))
160 IF TI<Q THEN 160
As it is, we have to check that the user doesn't
hit a key before the tone is sounded. Commands
1 60, 1 70, 340 and 350 are included simply to
check for this possibility.
The rest of the program is now completely
straightforward. The value of Tl at the beginning
of the reaction time period is stored in X, and
commands 240 and 250 are used to wait for the
user to hit a key.
Study the program carefully and make sure
you understand every command.
Experiment 15. 1 Completed
EXPERIMENT
15-2
Write a 'stopwatch' program. When the user
hits the 'B' key, the program starts timing.
When he strikes 'S', it stops and displays the
time taken, in seconds.
Your program should display instructions, so
that it can be used by anyone without further
explanation.
Hint: use GET and Tl.
Write a program which imitates someone
tossing a coin. Every time the user presses a
key, the program displays either "HEADS"
or "TAILS" at random.
Experiment 15.2 Completed
Now check your answers in Appendix B.
Random numbers are useful in program-
ming games of chance, such as dice, fruit
machines, and so on. All these programs follow
the same basic pattern, which for one 'throw' or
'spin' is like this
122
Let's illustrate this idea with the old game of
crown and anchor*. This is played with three dice
and a board divided into six squares*:
*Crown and anchor dice usually have different
symbols, but this doesn't affect the principle of
tnegame.
The piqyer puts his bet on any o ne of t he
squares. For instance he might back with
£5. Then the ba nker th rows all three dice. If one
of them shows , the player gets back
double his stake money: if two of the dice come
FT
up with L*J , the player gets triple the original
stake, and if shows on all three dice, the
player is rewarded wjth four times his stake. All
these rewards incl ude th e original stake. On the
FT
other hand, if no I *l comes up, the player
loses his stake.
The program for playing one throw of crown
and anchor is given below. Using the glossary
you should have no trouble in following it:
S: Player's stake
N: Number backed by player
°' \
D2 > Results of throwing 3 dice
D3 '
C: Number of dice showing N, the player's
number.
10 INPUT "STAKE"; S
20 INPUT "NUMBER BACKED (1 -6)"; N
30 Dl = INT(1+6*RND(0))
40 D2 = INT(1 +6*RND(0))
50 D3 = INT(1 +6*RND(0))
60C =
70IFD1ONTHEN90
80C = C+1
90IFD2ONTHEN110
100C = C+1
110 IF D3<>N THEN 130
120C=C+1
130 PRINT "DICE THROWN:"; Dl ; D2; D3
140 IF C<>0 THEN 170
150 PRINT "YOU LOSE"
160 GOTO 180
1 70 PRINT "YOU RECEIVE"; S*(C+l);"POUNDS"
180 STOP
Throw 3 dice
Count number of dice
showing number backed
by player
Display results
Very few gamblers stop short at a single
throw. Usually people start with a certain amount
of capital ana keep playing until they are broke
or — very rarely — the banker runs out of money.
Gambling programs on the VIC are better if
they imitate complete sessions of this type.
Initially the player is given a certain amount of
"money" (I ike £1 00) , and is then a I lows to play as
long as he likes, or until his money is used up. A
flow chart for such a game is shown below:
is/-)
Use this flow chart to modify the crown and
anchor program so that it starts the user off with a
capital of £100, and lets him play as long as he
likes. When your program is complete, run it
several times, and decide for yourself whether
you would rather be a player or a banker!
Yes
> >
Display:
YOU'RE BROKE!
Experiment 15.3 Completed
EXPERIMENT
15-4
Write a program to imitate any other game
of chance you know: craps, pontoon, etc.
Embellish your program with pictures of dice or
of cards, suitable sounds, and so on.
Experiment 15.4 Completed
Appendix B contains a 'craps' program for
you to try out.
AFTERWORD
u
AFTERWORD
Congratulations on reaching the end of the
course! By now you have gained a good
knowledge of the principles of programming,
and you'll be able to design and write programs
for a wide range of interesting problems and
computer applications. I hope that you've also
cultivated the habit of careful, thoughtful design,
of keeping and filing flow charts, glossaries and
notes for your programs. It is this quality of
planning and self-organisation that sets apart the
really competent programmer from the others.
At this stage, you have reached a half-way
point in your study of BASIC. There are many
important problems which need parts of the
language you haven't yet covered. For instance,
you may want to program moving pictures on the
screen, or to sort people's names into alphabetical
order, or to store them on a cassette tape. These
topics, and many others are fully explained in the
second book of this series, entitled
INTRODUCTION TO BASIC (Part II)
This book is in the same style as the one you have
just finished, and will complete your knowledge
of the BASIC language.
Programming — as we said in the introduc-
tion — is a very broad subject. Now that you have
made a start, you should broaden your
knowledge in three ways:
(a) Read as widely as you can. Most of the
popular computer magazines particularly
VIC Computing are worth looking at. Books
on programming are also worth reading,
even if they don't refer specifically to the VIC.
(b) Join a local computer club. There are VIC
user groups being set up all over the country
and details are given in the magazine VIC
Computing.
(c) Work at your programming. Practice
constantly, and aim for perfection. Design
your programs so that they are robust, and
usable by anyone without special instruction.
Write them so that you can be proud, not
ashamed, to display the inner workings to
another computer expert.
One last point. You have found a fascinating
hobby, and perhaps a life-long profession.
Remember that with the advantages of knowing
about computers, there also comes a responsi-
bility to see that they are used humanely and
wisely. No one wants a computer-controlled
society with little work and no freedom, and it is
now up to you — among others — to avoid it.
u
APPENDICES
APPENDIX
A
PAGE 129
APPENDIX
B
135
APPENDIX
C
149
APPENDIX
A
VIC is a computer capable of large-scale
mathematical calculations; as a matter of
historical interest it can do arithmetic consider-
ably faster than most large-scale computers
installed before 1960!
This appendix outlines some of the mathe-
matical facilities of the VIC. You only need to read
the appendix and understand the material in it if
you plan to use the computer for calculations in
Mathematics, Science or Engineering. Some of
the features described are quite simple, and can
easily be grasped by anyone who remembers the
elementary arithmetic they learned at school.
Other features need some more background
knowledge, such as that covered by an A-level
course in Mathematics. You need only go as far
as your knowledge and confidence will take you,
but you are expected to have read all the units in
the body of the course.
1. Expressions
The expressions first mentioned in Unit 4 are
very simple examples of a more general facility.
Thus in the commands
A=M
B = B+1
C = ( (X + Y) - 34.7/(Q-3) )*(Z-3)t2
the underlined portions are all expressions which
the VIC works out on your behalf.
Expressions are built up of three types of
element:
Values: numerical variables or numbers
such as
B,X,Y,34,34.7
Operators: the signs + - * / and |
(f means "raised to the power")
Brackets: ( and )
Expressions in BASIC are written in the same
way as in ordinary algebra, and have the same
meaning. There are four minor differences:
• BASIC expressions are in capitals instead of
small letters.
• Exponentiation ("raising the power") must
be shown with the f sign, because the VIC
screen doesn't let you write small numbers
above the line. Instead of "3 2 ", you would
put"3f2".
• Multiplication must always be shown using
the * sign. In BASIC, you would write "3*A",
not "3A" as in conventional algebra.
This rule can be a source of mistakes which
are hard to find. If you put BA where you
mean B*A,the machine will assume that you
are talking about a new variable called BA.
It won't report a syntax error, but it will
produce the wrong answer!
• Division is written A/B, not -g. If either the
numerator or the denominator of the fraction
is a complicated expression, you must
delimit it with brackets. The correct way
of writing |±| in BASIC is (3+5)/(7+8). If
you leave out the brackets and put3+5/7+8
the rules of precedence (which are given in
the next paragraph) will make the machine
treat this expression as 3+ y- + 8.
When the VIC works out an expression, it
takes the f signs first, then the multiplications and
divisions, ana lastly the additions and subtrac-
tions, working from left to right in each case.
Anything in brackets is worked out first. These a re
called the rules of precedence, and they give the
same results as ordinary school algebra.
The value of numbers in expressions do not
have to be integers (i.e. whole numbers) but can
be decimals. The VIC works to an accuracy of
about 8 decimal digits, which means that many
fractions (such as V3 or V7) can't be represented
exactly. You can expect small 'rounding' errors in
some arithmetic commands, so that a result which
you expected to be exactly 7 may come out as
"6.99999998".
To test your understanding of expressions,
work through the following examples, and
predict what the VIC will display in each case.
Assume that X = 3 and P = 7.
COMMAND
PREDICTED RESULT
ACTUAL RESULT
PRINT3 + 12— 6— 4
PRINT4 + 3*2
PRINTX + P— 3
PRINTS + 12/6— 3
PRINT 11/5— 7/4
PRINT4|2— 2f4
PRINT3 + 2|3 — 3|2
PRINT2 f X— P
PRINT3 + 12— (6 — 4)
PRINT5 + 12/(6 — 3)
PRINT (P + X)|(l— X)
PRINT4|2— 3 10
PRINT (P|2 — X| 2)/ 3
Now check your results on the VIC.
Remember to set the values of P and X before
you start.
In BASIC, expressions are most commonly
used in PRINT and LET commands. Here is a
simple program which inputs two numbers U
ana V, and displays a value F calculated
according to the 'lens' formula:
V U
10 INPUT "V";V
20 INPUT "U";U
30 PRINT "F="; 1/(1 /V+l/U)
40 STOP
Example 1
Write a program which reads two values V
and R, and which displays the value of the
V 2
formula A =
R
Example 2
Write a program which displays the values
of the formula y = — - — for values of x between
1+x 2
and 2, going up in steps of 0.2
(Hint: use a FOR loop like this:
FORX = 0TO2STEP0.2
NEXTX )
(The actual answers are given at the back of Appendix B.)
2 Standard Functions
Like most calculators, the VIC has a set of
'scientific' functions. A useful one is the square
root. This is abbreviated to SQR, and can be
included in expressions like these:
PRINT SQR(5)
or PRINT SQR(B|2+C|2)
The quantity in brackets is called the
argument of the function. In the case of SQR the
argument must be zero or positive.
Here is a program which displays the square
roots of all numbers between 1 00 and 115.
10 PRINT "N"; "SQR(N)"
20 FORN=100TO115
30 PRINT N;SQR(N)
40 NEXT N
50 STOP
Example 3
If the lengths of three sides of a triangle are
a, b and c, the area a of the triangle is given by the
formula a = >/s(s — a) (s— b) (s — c) where s is the
semi-perimeter, (a+b+c)/2.
Write a program which inputs three
numbers. If they can be the sides of a real triangle
the program displays the area of the triangle;
otherwise (e.g. if the numbers are 1 , 1 , 1 0) the
program displays an appropriate message.
(Hint: if the lines don't form a triangle the
value of s (s — a) (s — b) (s — c) is negative!)
Some of the more important mathematical
functions are given below. Read through them,
but do not feelobliged to learn them by heart—
you can always refer back to the list later.
SIN(X)
COS(X)
TAN(X)
ATN(X)
Trigonometrical functions. The
arguments must be in radians.
(1 degree = jt/180 radians)
The arc-tangent of X. The result is in
radians, between -tt/2 and jt/2.
LOG(X) The natural logarithm of X (Log to the
basee).
X must be positive
EXP(X) Equivalent to ex
ABS(X) The modulus of X (X if X > 0;
otherwise — X)
INT(X) The largest whole number equal to or
less than X. Note that:
INT (3.5) = 3
INT (-3.5) = -4
Now check your answer in Appendix B.
You can also use the keyboard symbol n
instead of the number 3. 141 59265 . .
Here is an example to show the use of some
of these functions.
A ladder can have its length changed from 4
metres to 5 metres in steps of 20 cms. It is placed
with its base 2.5 metres from a vertical wall, and
its top against the wall. Write a program to
display the angle of the ladder with the horizontal
for each of its 6 possible lengths.
First we do the mathematics, using a
diagram. We use x to indicate the length of the
ladder, and h to be the height of the top of the
ladder, and a to be the angle with the horizontal.
\
\ i
k
\
\
\
^ 1
i
\
\
\
V \ \ \ \ \ K \ \ \ K <
— ^ —
-2.5m-
h = V x 2 — (2.5) 2 (by Pythagoras)
a = arc tan (h/2.5) (in radians)
or a = (1 80/jt) * arc tan (h/2.5) in degrees.
Next we write the program, which has a
simple looped structure:
10 PRINT" LENGTH"," ANGLE"
20 FOR X=4 TO 5 STEP 0.2
30 H = SQR(X|2— 2.5|2)
40A=(180/jr)*ATN(H/2.5)
50 PRINT X, A
60 NEXT X
70 STOP
One of the most useful functions is INT. We
can use it to tell whether one number divides
another exactly. If X is an exact multiple of Y, then
the condition
X/Y = INT(X/Y)
will be true; otherwise it won't.
A number is a prime if it has no divisors
except itself and 1 . The following program calcu-
lates and displays prime numbers from 3 up to
any value set by the user:
10 INPUT "HIGHEST VALUE"; H
20FORN=3TOH
30FORJ=2TON— 1
40IFN/J = INT(N/J)THEN70
50 NEXT J
60 PRINT N;
70 NEXT N
80 STOP
Example 4
Study the prime number program (by tracing
if necessary) and work out how it works. Run it,
and time it for some value of H (say 500).
This method of calculating primes is actually
very slow. Design and incorporate some
improvements to make it run faster.
Hints: (a) No even numbers apart from 2
can be primes.
m {b) In testing for possible factors, it is
enough to go as far as the square
root of the number.
134
Now check your answer in Appendix B.
APPENDIX
B
135
UNIT:7
Experiment 7.1 :
a) T,T,T,T,F,F,F
b) F,F,T,T
Experiment 7.3:
(1) 10 P$= "★"
20 PRINT P$
30P$=P$+"*"
40 IF P$<>
THEN 20
50 STOP
(2) 1 PRINT "POUNDS", "DOLLARS'
20 PRINT
30P=10
40 PRINT P,1.77*P
50 P=P+2
60 IF P< 32 THEN 40
70 STOP
(3) 10 PRINT "CENT", "FAHR"
20 PRINT
30C=15
40F=1.8*C+32
50 PRINT C,F
60C=C+1
70 IF C< 31 THEN 40
80 STOP
Experiment 7.2:
Control
variable
Starting
value
Final
value
Increment
No. of times
round loop
X$
"A"
"ABBB"
"B"
4
P
10
+1
11
Y$
"Z"
"ZXYXY"
"XY"
3
R
5
14
3
4
C
27
7
—5
5
1
UNIT:8
txpenmentb. I:
a) PROGRAM COUNTER -H2hJ0*-30*-40"-S0"60
VARIABLES X: 5 Y: 7 Z: 12 W: 2
5 7 12 2
10X=5
BREAK IN 60
20Y=7
READY
30Z=X+Y
40 W=Y— X
50 PRINT X;Y;Z;W
60 STOP
PROGRAM COUNTER Afr3fr38rJflrJ&Jit!rJtirJ&rM
VARIABLES Q:^k3-3
SHE LOVES ME
10Q=1
SHE LOVES ME NOT
20 PRINT "SHE LOVES ME"
SHE LOVES ME NOT
30 PRINT "SHE LOVES ME NOT"
BREAK IN 60
40 Q=Q+1
READY
50 IF Q<3 THEN 30
60 STOP
Experiment 8.2:
a) Line 50 should be: 50 IF G<11 THEN 30
b) Line 30 should be: 30 A$=A$+"*"
Experiment 8.3:
c) Line 20: PRINT (not PRINT)
No RETURN after line 40
Line 60: IFX<13THEN40 (NOTX>13)
Line 70: STOP (not ST0P)
UNIT:9
Experiment 9.2:
10 POKE 3 6879,124
20 PRINT"
30 PRINT"
40 PRINT Tl$
50 GOTO 30
o
CRSR
V-
S— »
CRSR
Experiment 9.3:
5 REM FLAG OF ICELAND
1 CLR 1
1 anc
■ hqmeB
1 anc
MBam
1
CR_SR ■
CTRL
90 PRINT"
<- 22 spaces -
100J=J+1
110IFJ<4THEN90
UNITtll
Experiment 10.2:
a) 10 PRINT "TABLE PROGRAM"
20 INPUT 'TIMES"; N
30X=1
40 PRINT X; "TIMES"; N; "IS"; N*X
50 X=X+1
60 IF X<1 3 THEN 40
70 STOP
b) 1 PRINT "WHAT IS YOUR"
20 INPUT "SURNAME"; S$
30 PRINT "WHAT IS YOUR WIFE'S"
40 INPUT "CHRISTIAN NAME"; C$
50 PRINT "HER FULL NAME IS"
60 PRINT C$+" "+S$
70 STOP
Experiment 11.1:
LETS=1
DISPLAY
S,12*S
ADD 1 TO
S
TRUE
— < —
S<13
" FALSE
^STOP^
Experiment 1 1 .2:
139
i
DISPLAY: HOW
MANY DOORS?
INPUT D
DISPLAY: HOW
MANY WINDOWS?
I
INPUT W
I
DISPLAY: IS YOUR
HOUSE THATCHED OR
TILED?
INPUT R$
DISPLAY: ANSWER
THATCHED OR TILED
Glossary:
D: Number of doors
W: Number of windows
R$: THATCHED or TILED
TRUE
DISPLAY: RATES ARE
94+57*D+12*W
DISPLAY: RATES ARE
38+57*D+12*W
10 REM RURITANIAN RATES
20 PRINT "RATING PROGRAM"
30 INPUT "HOW MANY DOORS"; D
40 INPUT "HOW MANY WINDOWS"; W
50 PRINT "IS YOUR HOUSE"
60 PRINT "THATCHED OR"
70 INPUT "TILED ";R$
80 IF R$= 'THATCHED" THEN 140
90 IF R$= "TILED" THEN 160
100 PRINT "PLEASE ANSWER"
110 PRINT "THATCHED OR"
120 PRINT "TILED"
130 GOTO 50
140 PRINT "RATES ARE"; 38+57*D+12*W
150 STOP
160 PRINT "RATES ARE"; 94+57*D+12*W
170 STOP
Correct answers to three sample problems are:
a) 95 b) 155 c) 364
UNIT:12
Experiment 12.1:
10RS=0 )
20 INPUT "NUMBER OF INNINGS"; J f
30 FORQ = 1TOJ
40 INPUT "SCORE"; S
50 RS=RS+S
60 NEXT Q
70 PRINT "AVERAGE="; RS/J
80 STOP
Experiment 12.2:
CD
<D
in
n
O
3 o
l—
=
INPUT "NUMBER OF
BATCHES"; N
Glossary
N: Number of batches
S: Number of stamps in a batch
V: Value of each stamp in a batch
T: Running total due
Q: To count batch number
FORQ
1
N
1
DISPLAY:
"BATCH" Q
INPUT "NUMBER OF
STAMPS"; S
INPUT
"VALUE (EACH)";
V
T=T+S*V
-* ( Next Q )
r
DISPLAY:
'TOTAL DUE =";
T; PENCE
10T=0
20 INPUT "NUMBER OF BATCHES"; N
30FORQ=1TON
40 PRINT "BATCH"; Q
50 INPUT "NUMBER OF STAMPS"; S
60 INPUT "VALUE (EACH)"; V
70T=T+S*V
80 NEXTQ
90 PRINT 'TOTAL DUE="; T; "PENCE"
100 STOP
UNIT:13
Experiment 13.1 :
10 REM FIRE ENGINE
20 POKE 36878, 15
30 POKE 36876, 231
40 POKE 36875, 232
50 FOR M=l TO 400
60 NEXT M
70 POKE 36876, 224
80 POKE 36875, 223
90 FOR M=l TO 400
100 NEXTM
110 GOTO 30
10 REM POLICE SIREN
20 FOR J=0 TO 15
30 POKE 36878, 3+J/2
40 POKE 36876, 200+J
50 FOR K=1TO20
60 NEXT K
70 NEXT J
80 FORJ=1TO100
90 NEXT J
100FORJ=15TO0STEP— 1
110 POKE 36878, 3+J/2
120 POKE 36876, 200+J
130 FOR K=1TO20
140 NEXTK
150 NEXT J
160 GOTO 20
Experiment 13.2:
10 REM DIESEL TRAIN HORN
20 POKE 36878, 15
30 POKE 36876, 235
40 POKE 36875, 235
50 FORJ=1TO1000
60 NEXT J
70 POKE 36878,0
80FORJ=1TO100
90 NEXT J
100 POKE 36878, 15
110 POKE 36876, 240
120 POKE 36875, 240
130 FORJ=1TO1000
140 NEXT J
150 POKE 36878, 5
160 POKE 36876, 235
170 POKE 36875, 235
180FORJ=1TO1000
190 NEXT J
200 POKE 36875,0
210 POKE 36876,0
220 POKE 36878,0
230 STOP
1 REM JET FLYING OVERHEAD
20 FOR J=l 1 TO 1 00 STEP -0.2
30 V= 6000/(500+3*(J— 50)t2)
40 POKE 36878, V+3
50 POKE 36877, 225 +J/6
60 FORM=1TO50
70 NEXTM
80 NEXT J
90 POKE 36877,0
100 POKE 36878,0
110 STOP
UNIT:14
Experiment 14.1:
Input: "OLD
BALANCE"; B
Display:
TYPE DETAILS
OF CHEQUES.
USE TO END
Input:
"AMOUNT"; V
True
Set B=B— V
True
Display: YOUR
OVERDRAFT IS;
-B
B<0
.1
Display: YOUR
BALANCE IS ; B
STOP
B: Current balance
V: Each new transaction
10 REM.BANKING PROGRAM
20 INPUT "OLD BALANCE"; B
30 PRINT "TYPE DETAILS OF"
40 PRINT "CHEQUES. USE TO END'
50 INPUT "AMOUNT"; V
60 IF V=0 THEN 90
70 B=B— V
80 GOTO 50
90 IF B<0 THEN 120
1 00 PRINT "YOUR BALANCE IS £"; B
110 STOP
1 20 PRINT "YOUR OVERDRAFT"
130 PRINT "IS £";-B
140 STOP
Experiment 14.2:
(b)
143
Dis
descr
hea
play
iptive
ding
Input "NEXT
PRICE"; P
1 ' True
Display:
TOTAL TO BE
CHARGED IS; T
Glossary
P: Net price of clock
T: Total to be charged
T=P+VsP
T=P+4
T=P+y 4 P
10 REM CL OCK TAX
20 PRINT "BUB and B CLOCK TAX PROGRAM"
30 PRINT "GIVE NET PRICES"
40 PRINT "USE TO END"
50 INPUT "NEXT PRICE"; P
60 IF P=0 THEN 180
70IFP>=12THEN100
80 T= P+(1/3)*P
90 GOTO 140
100 IF P>=1 6 THEN 130
110T=P+4
120 GOTO 140
130T=P+ (1/4)*P
1 40 PRINT 'TOTAL TO BE CHARGED"
150 PRINT "IS ";T
160 PRINT
170 GOTO 50
180 STOP
Experiment 14.2:
c)
Display descriptive
heading
Input!
True
False
Display: "YOU MUST
GIVE AT LEAST ONE
NON-ZERO NUMBER"
Input X
True
True
L=X
Display: "LARGEST
NUMBER IS"; L
Glossary:
L: Largest number so far
X: Next number to be input
10 REM FIND LARGEST NUMBER
20 PRINT "GIVE NUMBERS ENDED"
30 PRINT "BY 0"
40 INPUT "NEXT"; L
50 IF L=0 THEN 130
60 INPUT "NEXT"; X
70 IF X=0 THEN 110
80 IF X<L THEN 60
90L=X
100 GOTO 60
110 PRINT "LARGEST IS"; L
120 STOP
1 30 PRINT "YOU MUST GIVE AT LEAST"
140 PRINT "ONE NON-ZERO NUMBER"
150 GOTO 20
(Note: The following "solution" won't work
if all the numbers are negative — that is, less than
zero.)
10 L=0
20 INPUT "NEXT"; X
30 IF X=0 THEN 70
40 IF X<L THEN 20
50 L=X
60 GOTO 20
70 PRINT "LARGEST IS"; L
80 STOP
Why not?
UNIT:15
Experiment 15.2 (1):
T=(TI— X)/60
Display
elapsed time
timeT.
GET A$
"B"
' True
False
Display:
'TIMING
STARTED"
X=
Tl
*
— *
GETA$
"S"
fTrue
False
Glossary:
A$: Keyboard character
X: Internal time at start of interval
(jiffies)
T: Elapsed time (seconds)
5 REM STOPWATCH
10 PRINT" BUB and
20 PRINT "STOPWATCH PROGRAM"
30 PRINT
40 PRINT 'TO START THE STOPWATCH'
50 PRINT "HIT THE B KEY"
60 PRINT 'TO STOP IT, HIT S"
70GETA$
80IFA$o"B"THEN70
90 X=TI
95 PRINT 'TIMING STARTED"
100 GET A$
110IFA$o"S"THEN100
120 T= (Tl— X)/60
1 30 PRINT "ELAPSED TIME WAS"
140 PRINTT; "SECONDS"
150 PRINT
1 60 PRINT "NOW HIT ANY OTHER KEY"
1 70 PRINT "FOR ANOTHER TIMING"
180 GET A$
190 IFA$= ""THEN 180
200 GOTO 10
Experiment 15.2 (2):
Display
heading
Display:
"WAIT FOR IT!'
T=0orl
at random
False
Display:
"HEADS"
Display:
'TAILS"
Glossary:
S$ Keyboard character
M: Used in loop to wait 2 seconds
T: (for Tails) or 1 (for Heads)
10 REM C OIN TOSS ING
20 PRINT" HB and
30 PRINT "HIT ANY KEY TO TOSS"
40 PRINT "YOUR COIN"
50GETS$
60 IFS$= " "THEN 50
70 PRINT "WAIT FOR IT!"
80 PRINT
90 FOR M=l TO 2000
100 NEXTM
110T=INT (0+2*RND(0))
120 IF T=l THEN 150
130 PRINT "TAILS"
140 GOTO 160
150 PRINT "HEADS"
160 PRINT
1 70 PRINT "HIT ANY KEY FOR"
180 PRINT "NEXT GO"
190 GET S$
200IFS$= ""THEN 190
210 GOTO 20
Experiment 15.4:
10 REM CR APS
20 PRINT" BUB and
30 PRINT "THE GAME OF CRAPS"
40 PRINT "IS PLAYED WITH TWO"
50 PRINT "DICE. FIRST YOU BET"
60 PRINT "AND THEN YOU THROW. IF"
70 PRINT "YOU GET A SCORE OF 7"
80 PRINT "OR 1 1 , YOU WIN. IF YOU"
90 PRINT 'THROW 2, 3 OR 12, YOU"
1 00 PRINT "LOSE. IF YOU THROW ANY"
110 PRINT "OTHER NUMBER YOU DONT"
1 20 PRINT "WIN OR LOSE STRAIGHT"
1 30 PRINT "AWAY: YOU KEEP ON"
140 PRINT 'THROWING UNTIL YOU"
150 PRINT "EITHER"
1 60 PRINT " THROW THE SAME AS YOU"
170 PRINT "DID FIRST TIME (AND"
180 PRINT "WIN)"
190 PRINT "OR"
200 PRINT " THROW A 7 (AND LOSE)"
210 PRINT
220 PRINT "HIT ANY KEY TO"
230 PRINT "CONTINUE"
240 GETA$
250IFA$= " "THEN 240
255 REM SET A$, B$, C$ TO LINES OF DICE
PICTURE
260 A$ = "<- 4 spaces -» r
<— 2 spaces -» ( ~\"
270 B$= "«-4 spaces -»• I «-3 spaces -»
| <- 2 spaces -> I «- 3 spaces -> \ "
280 C$ = " *- 4 spaces -* r \
«— 2 spaces — > f ^ "
285 REM GE T STARTIN G CAPITAL
290 PRINT" HUH and
300 INPUT "STARTING CAPITAL"; C
305 REM NOW START NEXT BET
310 PRINT "HIT ANY KEY FOR"
320 PRINT "NEXT BET"
330 GETR$
340IFR$= ""THEN 330
350 PRINT "YOUR CAPITAL NOW IS'
360 PRINT C
370 PRINT "HOW MUCH DO YOU"
380 INPUT "BET"; W
390 IF W<=C THEN 420
400 PRINT "YOU CANT AFFORD IT"
410 GOTO 310
415 REM ORGANISE FIRST THROW
420 PRINT" ■■■■and
FIRST THROW (BET = '
o
o
o
CRSR
CRSR
CRSR
JJ
-U-
. ^ .
;W; ")'
CRSR I CRSR I CRSR I CRSR
";A$
430 PRINT "I
440 FOR J=l TO 5
450 PRINT B$
460 NEXT J
470 PRINT C$
475 REM SHOW 1 0-59 DIFFERENT FACE PAIRS
480 Q=INT(10+50*RND(0))
490FORZ=1TOQ
500A=INT(1+6*RND(0)) "
510 B= INT(1+6*RND(0))
51 5 REM SOUND A NOTE WHICH DEPENDS
ON A AND B
520 POKE 36878, 15
530 POKE 36876, 254-A*B
540 PRINT
CRSR I CRSR I CRSR I CRSR I CRSR I CRSR
JJ 1 JJ 1 JJ
crsr |crsr|cr?r IcrsrTcrsr TcrTr Icrsr
olol=>l=>lolr>l=>
"A-
crsr ■ crsr Icrsr I crsr
B
545 REM WAIT A BIT
550 FORM=1TO50
555 NEXT M
560 NEXTZ
565 REM STOP SOUND
570 POKE 36876,0
580 POKE 36878,0
585 REM USE LAST VALUES OF A, B
590T=A+B
595 REM JUMP IF PLAYER WINS OUTRIGHT
600 IF T=7 THEN 1000
610 IFT=11 THEN 1000
615 REM JUMP IF PLAYER LOSES OUTRIGHT
620 IF T=2 THEN 1100
630 IF T=3 THEN 1100
640 IF T= 12 THEN 1100
645 REM ELSE ORGANISE MORE THROWS
650 PRINT
660 PRINT
670 PRINT
680 PRINT "YOU HAVE TO MAKE"
690 PRINT T; "BEFORE 7"
700 PRINT'
I HIT ANY KEY TO GO ON'
710 GET R$
720 IF R$^ " "THEN 710
o
O
o
■Cr
f>
■o
CRSR
CRSR
CRSR
CRSR
CRSR
CRSR
CRSR
JJ-
O
JJ-
JJ
J J-
-u-
JJ
730 PRINT" HUM and I
THROW (BET=";W; ")'
740 PRINT "MAKING"; T
NEXT
CLR
HOME
<: 1
r>
r>
° 1
CRSR I
JJ 1
CRSR
JJ
CRSR
•U-
CRSR
750 PRINT "I
760 PRINT A$
770 FOR J=l TO 5
780 PRINT B$
790 NEXT J
800 PRINT C$
805 REM SHOW 1 0-1 9 DIFFERENT FACE PAIRS
810Q=INT(10+10*RND(0))
820FORZ=1TOQ
830 A=INT(1+6*RND(0))
840B=INT(1+6*RND(0))
850 POKE 36878, 15
870 PRINT "
CLR
HOME
r>
CRSR
JJ-
-Tr
CRSR
O
f>
CRSR
JJ
CRSR I CRSR
ij 1 JJ
<=
Cz '
<= '
C= '
CRSR
CRSR
CRSR
CRSR
CRSR
=>
^>
=> .
';A ;
CRSR I CRSR I CRSR I CRSR
;B
880 FOR M=l TO 50
890 NEXT M
900 NEXTZ
905 REM SILENCE
910 POKE 36876,0
920 POKE 36878,0
925 REM IF A+B=T PLAYER WINS
930 IFA+B=TTHEN 1000
935 REM IF A+B=7 PLAYER LOSES
940 IF A+B=7 THEN 1100
945 REM ELSE PLAYER THROWS AGAIN
950 GOTO 700
990 REM PLAYER WINS
o
-Tr o
o
o
1>
o
CRSR
CRSR CRSR
CRSR
CRSR
CRSR
CRSR
■U
-u-
4 J.
1 000 PRINT'
YOU WIN"
1 005 REM ADD WINNINGS TO CAPITAL
1010C=C+W
1015 REM PAEAN OF PRAISE
1020 POKE 36878, 15
1030 FOR J=l TO 20
1040 POKE 36876, 240
1050 FOR M=l TO 25
1060 NEXT M
1070 POKE 36876,0
1080 FOR M=l TO 25
1085 NEXTM
1090 NEXT J
1095 GOTO 310
1100 REM PLAYER LOSES
o
r>
O
o
f>
Ct
CRSR
CRSR
CRSR
CRSR
CRSR
CRSR
CRSR
O
•U-
•U-
4J.
1110 PRINT "I
YOU LOSE"
1 11 5 REM CHIRP OF TRIUMPH
11 20 POKE 36878, 15
1 1 30 FOR J=220 TO 1 27 STEP —1
11 40 POKE 36874, J
11 50 POKE 36875, J
1160 FOR M=l TO 5
1170 NEXTM
1180 NEXT J
11 90 POKE 36878,0
1 1 95 REM TAKE LOSS FROM CAPITAL
1200 C=C— W
1210 IF C>0 THEN 310
1 220 PRINT "YOU ARE NOW BROKE"
1230 STOP
APPENDIX A
PROBLEM SOLUTIONS
Example 1:
10 INPUT V
20 INPUT R
30 PRINT "A="; VT2/R
40 STOP
Example 2:
10 PRINT "X FORMULA"
20 FOR X=0 TO 2 STEP 0.2
30 PRINT X; 1/(1 +X|2)
40 NEXT X
50 STOP
148
Example 3:
1 PRINT "GIVE THE THREE SIDES'
. 20 INPUT "A"; A
30 INPUT "B";B
40 INPUT "C";C
50 S= (A+B+Q/2
60 X= S*(S— A)*(S— B)*(S-C)
70 IF X<0 THEN 100
80 PRINT "AREA IS"; SQR(X)
90 STOP
1 00 PRINT "THESE ARE NOT THE"
1 1 PRINT "SIDES OF A TRIANGLE"
120 STOP
Glossary:
A, B, C: Three "sides" of triangle
S: Semi-perimeter
X: Square of area (if any)
Example 4:
1 REM SLIGHTLY FASTER VERSION
20 INPUT "HIGHEST VALUE"; H
30 FOR N=3 TO H STEP 2
40 Q= SQR (N)
50FORJ=2TOQ
60 IF NAM INT (N/J) THEN 90
70 NEXT J
80 PRINT N;
90 NEXT N
100 STOP
APPENDIX
c
Error Messages
This list covers errors which can arise if you
use the BASIC facilities described in this book.
Other errors can occur if you run programs of a
more advanced nature.
Division by Zero
Dividing a number by zero is not allowed.
The error may arise in commands like
10A = 5/0
or 20B = Q/(J-J)
Extra Ignored
If you type too many items (numbers or
strings) in reply to an INPUT command, the extra
ones will be ignored. The program doesn't stop.
Illegal Quantity
A number used in a command is too large (or
too small). For instance, any number you POKE
into a location must be in the range to 255.
This error can occur in commands like
10 POKE 36878, 1234
or 20 J = 300
30 POKE 36876, J
Load Error
Your program is not loading correctly from
the cassette recorder. Try cleaning the reading
head. Alternatively, the program may not have
been recorded correctly in the first place, or the
tape may have been damaged by a magnetic
field.
Next Without For
The FOR-NEXT structure of your program is
wrong.
Out of Memory
The computer has run out of space in the
memory. This only happens with very long
programs, or ones which use large amounts of
data.
Redo from Start
If an INPUT command expects a number,
and you type something which isn't a number, the
computer will display this message and let you try
again.
String Too Long
A string formed by concatenation is larger
than 255 bytes.
Syntax Error
A "command" has broken the rules of BASIC
grammar. Possible causes are mismatched
brackets, mis-spelled keywords, or elements of
expressions in the wrong order.
Type Mismatch
This means that a number has been used
instead of a string, or vice versa.
Verify Error
The verification process has failed. Try
SAVE'ing the program again.
I !
u
INDEX
Altering programs
37-40
Arithmetic operators
27,129
Average
107
Background colour
16,17
Back-up storage
41
Bank
73,110
Bars voice
101,105
BASIC
23
Blank lines
48
Brackets
129
Bytes
2,31
Cassette Recorder
3,40
Cassette Tape
3,40
Characters
2
Clocks
113
CLR/HOME key
7,10,65-71
Colour
15,65-71
Colour codes
16,17,65-71
Colour keys
4,16,65-71
Comma
24,48
COMMODORE key
7,8,9,16
Concatenation
27
Conditions
45-46,47,55,59
Control function
65,67
Control variable
48,93
Correcting typing mistakes
11
Cricket
96,97
Crown and Anchor
122
CRSR ■
WbSM key
7,10,65-71
-n - ■
CRSR
u M3SM
7,10,65-71
CTRL key
4,7,16,18,32,65
Cursor
2,8,10,12,15,18,39,65
Cursor control keys
DATA command
Dealer
Division
Duration of sound
Editing program
Environment
Exponentiation
Expression
Final value
Flags
Flexible programs
Flow chart
Football
FOR command
Frame colour
Function keys
Gambling
Games
GET command
Glossary
GOTO command
Graphics
Headings
10
39
2,3
24,129
102
37-40
1
129
24,27,95,129-131
49,93
18,19,70
73-76
80,88,93
26,108
93-98
16,17
7
111
117-124
119
86
31-34,58,81
8,11
48
Idle loop
IF command
INPUT command
INST/DEL key
Internal clock
Internal timer
Kemeny & Kurtz
Keyboard
Keyword
Jiffy
Labelled command
Label numbers
LET command
LIST command
LOAD command
Loop
Loop body
Loop stop
Lower-case letters
Machine breakdowns
Memory
Message
Multiplication
Music
Names of variables
Nested loop
NEW command
NEXT command
Noise
Normal mode
Null string
Numbers
Numeric variable
Offenbach
Pictures
Pitch of VIC voices
POKE command
Post Office
Power lamp
Power supply
PRINT command
Program
Program control
Program design
Programming errors
Program pointer
Programming tools
Program tracing
Pyramid of cannon balls
Quartz crystal
Quote mode
Quote symbols
Random (RND) function
Reaction time
READY.
Relationships
REM command
Repeating keys
Repetition
RESTORE key
RETURN key
Reverse field
Reverse mode
Robust program
Rounding errors
RUN command
102
45-47,58,79,111
73-76,107-109,119
3,7,11,39
68
120
23
2,7-12
16,23,24
120
31
31,32,51
26-28,33,55,58
31,37-38
3,41
33,47,50,59,93
48,93
67,69
9
62
2,26,31,40
2,7
24,129
4
27
103
31
93-98
101,105
18
119
24,45
27,45
4
7,20,65-70
101
16,17,101-105
97
1,2
1
2,23-25,48,58,67,70
3,26
45-55
50,57,75,83,95,107
42,57
57
37
57-63
95
68
65
3,7,24,65
119,120
117
3
45
38,86
10,119
32
4,7,67,75,102
2,3,7,23,31
18,65
18,65
112
130
3,32
Rl IN/STOP km/
0,1 ,OA,t J, 1 UZ
pwc OFF l^ov
ivvo urr Key
1 fl 9ft AA tn
DWC f^KI L ou
i\vo Key
1 fl OC\ X7 XO 7fl
C A\/F fr^ rm m
Jnvt cornrnuna
4fl 41
Screen
z
Cam 1 Inn
94 V) 7fl
onir I Key
"3. 7 ft Q
SHIFT LOCK k*»v
017
Qi onro
1 uz
Sound
101-105
1 V 1 1 \JtJ
OA
AH
oiunuuru Tunciions
IOZ
oTurnng voiue
4ft 0"?
OQ.O/C IfM 10*5
1 f JO
Stored commnnd*;
31-32
Strinn*;
94 45 ^.5
oiling vunaoies
97 4<\
Z/,4D
oyniDOi Keys
7
oyniux error
■3 9<;
«j,Z3
1 CI IUI VUILC
Tprminn+nr
1 CI 1 1 III IUIUI
ins
TI
1 1
Tin
Tl$
TiminQ
1 iU 1 z 1
1 reoie voice
IUI
1 1 UU VJ 1 C dllUUIIIIU
9
z
Ti minn XV
1 ill III IU 1 V
1 4
TV cot
1 v sei
1
1
1 yp'i'y iiiibiuKes
1 1
ubci ^ui u pruyrom^
47 7"? 1 Dft
H/ ,/o,\\)0
vuriuDies
OA.
AO
VERIFY command
» UIMI I 1 II I IUI IU
41
*T 1
Voices
101
Volume control
1A1 TOO 1f\A
\\J\,\ (Jo- 1 U4
Write permit tabs
40
= sign
55
u
u
u
□
u
u
u
□
u
u
u
u
□
□
□
u
□
LJ
u
□
u
u
□
□
□
□
u
□
u
u
u
u
u
u
c Commodcfti Electronics Limited
c Copyright Andrew Colin 1932.
A 'I r ig*i'E rBs=r- yf;c | sj p art f ff, e piograrn^ or
manual included in this worit moy be duplicated,
copied, Ixcmsmtrted or repr oduced «n any Form or
r >y nny mecn r > wi rhotjl tfie pi lOf wi itien pwmiwioo
oFHivouiho*.
■ ■
■ I
Commodore International Limited
487 Devon Park Drive, Suite 300,
Wayne, PA 19067
COMPUTER